Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add editor playback sync selftest with headless audio sink and CI wiring
Richie McIlroyf8b8fe8adaf4
diff --git a/.github/workflows/sync-tests.yml b/.github/workflows/sync-tests.ymlindex 6527385bf..1f7de7617 100644--- a/.github/workflows/sync-tests.yml+++ b/.github/workflows/sync-tests.yml@@ -40,6 +40,8 @@ jobs:- windows-2022- ubuntu-24.04runs-on: ${{ matrix.runner }}+ permissions:+ contents: readsteps:- name: Checkoutuses: actions/checkout@v4@@ -70,11 +72,18 @@ jobs:shell: pwshrun: Add-Content -Path $env:GITHUB_PATH -Value "${{ github.workspace }}\\target\\ffmpeg\\bin"+ - name: Install software Vulkan driver (Linux)+ if: runner.os == 'Linux'+ run: |+ sudo apt-get update+ sudo apt-get install -y mesa-vulkan-drivers libvulkan1+- name: Timestamp pipeline unit + property testsshell: bashrun: |cargo test --locked -p cap-timestamp -p cap-enc-ffmpegcargo test --locked -p cap-recording --lib+ cargo test --locked -p cap-rendering- name: Synthetic device matrixid: matrix@@ -86,6 +95,15 @@ jobs:run: |cargo test --locked -p cap-recording --test sync_matrix -- --nocapture+ # Verifies the editor's playback machinery (decoders, frame scheduling,+ # audio pipeline) preserves sync. The fixture recording is generated+ # through the real recording pipeline, so no capture hardware is needed;+ # rendering uses the platform's software adapter where no GPU exists.+ - name: Editor playback sync harness+ shell: bash+ run: |+ cargo run --locked -p cap -- selftest playback --json+- name: Report findingsif: always()shell: bashdiff --git a/Cargo.lock b/Cargo.lockindex 10f153f69..33d20ab58 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1165,9 +1165,12 @@ dependencies = ["cap-automation","cap-camera","cap-cli-install",+ "cap-editor","cap-export",+ "cap-media-info","cap-project","cap-recording",+ "cap-timestamp","chrono","cidre","clap",@@ -1180,6 +1183,7 @@ dependencies = ["image 0.25.8","kameo","libc",+ "relative-path","reqwest 0.12.24","scap-screencapturekit","scap-targets",diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.tomlindex 5096c73ae..082df3cb9 100644--- a/apps/cli/Cargo.toml+++ b/apps/cli/Cargo.toml@@ -8,7 +8,11 @@ clap = { version = "4.5.23", features = ["derive"] }clap_complete = "4.5.38"cap-project = { path = "../../crates/project" }cap-recording = { path = "../../crates/recording" }+cap-editor = { path = "../../crates/editor" }cap-export = { path = "../../crates/export" }+cap-media-info = { path = "../../crates/media-info" }+cap-timestamp = { path = "../../crates/timestamp" }+relative-path = "1.9.3"cap-automation = { path = "../../crates/automation" }cap-camera = { path = "../../crates/camera" }cap-cli-install = { path = "../../crates/cli-install" }diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 7ee005824..af1f9e4f2 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -446,6 +446,17 @@ fn main() {.name("cap-cli-runtime".to_string()).stack_size(TOKIO_WORKER_THREAD_STACK_SIZE).spawn(move || -> Result<(), String> {+ // serve_main_thread blocks the main thread until this shutdown+ // runs; a drop guard keeps that true on every exit path, including+ // the runtime failing to build and panics unwinding out of run().+ struct PatternShutdown;+ impl Drop for PatternShutdown {+ fn drop(&mut self) {+ selftest::pattern::shutdown_main_thread_runner();+ }+ }+ let _pattern_shutdown = PatternShutdown;+let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().thread_stack_size(TOKIO_WORKER_THREAD_STACK_SIZE)@@ -453,7 +464,6 @@ fn main() {.map_err(|e| format!("Failed to build Tokio runtime: {e}"))?;let result = runtime.block_on(run(cli));- selftest::pattern::shutdown_main_thread_runner();if exit_after_success && result.is_ok() {// Successful export/preview workers have already written their output by here.// Exiting directly avoids Windows GPU/MediaFoundation teardown crashes in the@@ -466,6 +476,16 @@ fn main() {result});+ // A failed spawn means nothing will ever call shutdown_main_thread_runner, so the+ // pattern server below would block forever — bail out before serving.+ let runtime_thread = match runtime_thread {+ Ok(handle) => handle,+ Err(e) => {+ eprintln!("error: Failed to spawn CLI runtime thread: {e}");+ std::process::exit(1);+ }+ };+if let Some(rx) = pattern_rx {selftest::pattern::serve_main_thread(rx);}@@ -473,13 +493,7 @@ fn main() {// Surface failures as a clean, unquoted `error: ...` line on stderr (the default// `Result`-returning main prints `Error: "debug-quoted"`, which is noisy for humans and brittle// for agents scraping stderr). clap already exits 2 for usage/parse errors before we get here.- let outcome = match runtime_thread {- Ok(handle) => handle.join(),- Err(e) => {- eprintln!("error: Failed to spawn CLI runtime thread: {e}");- std::process::exit(1);- }- };+ let outcome = runtime_thread.join();match outcome {Ok(Ok(())) => {}diff --git a/apps/cli/src/selftest/measure.rs b/apps/cli/src/selftest/measure.rsindex bd4b0b0aa..defc65cc2 100644--- a/apps/cli/src/selftest/measure.rs+++ b/apps/cli/src/selftest/measure.rs@@ -60,6 +60,13 @@ pub fn video_flash_onsets(path: &Path) -> Result<Vec<f64>, String> {take_frame(&decoded);}+ flash_onsets_from_luma(&samples)+}++/// Flash onsets from a time-ordered `(seconds, mean luma)` series, shared by+/// the file analyzers and the playback harness (which samples luma at the+/// renderer's presentation boundary).+pub fn flash_onsets_from_luma(samples: &[(f64, f64)]) -> Result<Vec<f64>, String> {if samples.len() < 10 {return Err(format!("only {} video frames decoded; recording too short to analyze",@@ -85,7 +92,7 @@ pub fn video_flash_onsets(path: &Path) -> Result<Vec<f64>, String> {let mut onsets = Vec::new();let mut armed = true;- for (t, luma) in &samples {+ for (t, luma) in samples {if *luma >= on && armed {onsets.push(*t);armed = false;@@ -178,6 +185,12 @@ pub fn audio_beep_onsets(path: &Path) -> Result<AudioOnsets, String> {take_frame(&decoded);}+ beep_onsets_from_mono(mono, sample_rate)+}++/// Beep onsets from a mono sample stream, shared by the file analyzers and+/// the playback harness (which taps samples at the device handoff).+pub fn beep_onsets_from_mono(mut mono: Vec<f32>, sample_rate: u32) -> Result<AudioOnsets, String> {if sample_rate == 0 || mono.len() < sample_rate as usize {return Err("audio track too short to analyze".to_string());}diff --git a/apps/cli/src/selftest/mod.rs b/apps/cli/src/selftest/mod.rsindex 9df4bd0c6..4edb0b19c 100644--- a/apps/cli/src/selftest/mod.rs+++ b/apps/cli/src/selftest/mod.rs@@ -5,6 +5,7 @@pub mod measure;pub mod pattern;+pub mod playback;use std::{path::{Path, PathBuf},@@ -29,6 +30,7 @@ const PASS_TOTAL_DRIFT_MS: f64 = 20.0;const PASS_MAD_MS: f64 = 20.0;const WARN_OFFSET_MS: f64 = 120.0;const WARN_TOTAL_DRIFT_MS: f64 = 40.0;+const WARN_MAD_MS: f64 = 40.0;const MAX_RAW_EXPORT_DELTA_MS: f64 = 25.0;const MIN_BEEP_SNR: f64 = 8.0;/// Extra offset budget for the acoustic microphone path: sound flight time@@ -49,6 +51,9 @@ pub enum SelftestCommands {/// Record a test pattern and verify audio/video sync end-to-end#[command(name = "av-sync")]AvSync(AvSyncArgs),+ /// Verify the editor playback path preserves audio/video sync+ #[command(name = "playback")]+ Playback(playback::PlaybackArgs),/// Internal: measure flash/beep onsets in an existing recording or export#[command(name = "analyze", hide = true)]Analyze(AnalyzeArgs),@@ -135,6 +140,7 @@ impl SelftestArgs {pub async fn run(self, json: bool) -> Result<(), String> {match self.command {SelftestCommands::AvSync(args) => run_av_sync(args, json).await,+ SelftestCommands::Playback(args) => playback::run_playback(args, json).await,SelftestCommands::Analyze(args) => run_analyze(args),}}@@ -174,7 +180,9 @@ async fn run_av_sync(args: AvSyncArgs, json: bool) -> Result<(), String> {// the progress output; measurement errors are surfaced through Results.ffmpeg::util::log::set_level(ffmpeg::util::log::Level::Quiet);- let pattern_secs = args.duration.clamp(10, 120);+ // The floor guarantees enough events for measure_sync's minimum after the+ // first event is dropped: 14s -> 7 events -> 6 usable pairs.+ let pattern_secs = args.duration.clamp(14, 120);let events = (pattern_secs / EVENT_PERIOD.as_secs()).max(3) as u32;let spec = PatternSpec {settle: SETTLE,@@ -550,7 +558,7 @@ fn classify(m: &SyncMeasurement) -> Verdict {let drift = m.total_drift_ms.abs();if offset <= PASS_OFFSET_MS && drift <= PASS_TOTAL_DRIFT_MS && m.mad_ms <= PASS_MAD_MS {Verdict::Pass- } else if offset <= WARN_OFFSET_MS && drift <= WARN_TOTAL_DRIFT_MS {+ } else if offset <= WARN_OFFSET_MS && drift <= WARN_TOTAL_DRIFT_MS && m.mad_ms <= WARN_MAD_MS {Verdict::Warn} else {Verdict::Fail@@ -569,7 +577,10 @@ fn classify_mic(m: &SyncMeasurement) -> Verdict {&& m.mad_ms <= PASS_MAD_MS{Verdict::Pass- } else if offset <= WARN_OFFSET_MS + MIC_EXTRA_OFFSET_MS && drift <= WARN_TOTAL_DRIFT_MS {+ } else if offset <= WARN_OFFSET_MS + MIC_EXTRA_OFFSET_MS+ && drift <= WARN_TOTAL_DRIFT_MS+ && m.mad_ms <= WARN_MAD_MS+ {Verdict::Warn} else {Verdict::Fail@@ -649,7 +660,7 @@ fn evaluate(if let Some(export_m) = &export_m {let export_verdict = classify(export_m);- if export_verdict > verdict && export_verdict == Verdict::Fail {+ if export_verdict != Verdict::Pass {reasons.push(format!("export offset {:+.0} ms / drift {:+.0} ms over {:.0}s",export_m.median_offset_ms, export_m.total_drift_ms, export_m.span_secsdiff --git a/apps/cli/src/selftest/pattern.rs b/apps/cli/src/selftest/pattern.rsindex 2aee46c0a..d96b3037b 100644--- a/apps/cli/src/selftest/pattern.rs+++ b/apps/cli/src/selftest/pattern.rs@@ -43,6 +43,19 @@ impl PatternSpec {pub fn total_runtime(&self) -> Duration {self.settle + self.period * self.events + Duration::from_millis(500)}++ /// Event onsets relative to the pattern epoch. Nominally periodic, with a+ /// deterministic per-event jitter of up to ±300 ms: a perfectly periodic+ /// schedule would let an A/V shift of exactly one period pair every flash+ /// with the wrong beep and alias to a zero measured offset.+ pub fn event_offsets_secs(&self) -> Vec<f64> {+ (0..self.events)+ .map(|k| {+ let jitter = (u64::from(k).wrapping_mul(2_654_435_761) % 601) as f64 / 1000.0 - 0.3;+ (f64::from(k) * self.period.as_secs_f64() + jitter).max(0.0)+ })+ .collect()+ }}#[derive(Debug)]@@ -111,9 +124,8 @@ pub async fn request_pattern(spec: PatternSpec) -> Result<PatternReport, String>struct BeepState {epoch: Instant,- period_samples: u64,- beep_samples: u64,- events: u32,+ /// Sorted (start, end) sample windows of each beep, relative to epoch.+ event_windows: Vec<(u64, u64)>,sample_rate: u32,channels: usize,/// Absolute sample index of pattern epoch, fixed on the first callback.@@ -155,24 +167,37 @@ impl BeepState {let rel = abs_sample - epoch_sample;let mut value = 0.0f32;if rel >= 0 {- let event = (rel as u64) / self.period_samples;- let within = (rel as u64) % self.period_samples;- if event < u64::from(self.events) && within < self.beep_samples {- // 1 kHz tone with a 2 ms fade-in/out to avoid clicks while- // keeping the onset sharp for detection.- let t = within as f32 / self.sample_rate as f32;- let fade_len = 0.002 * self.sample_rate as f32;- let fade_in = (within as f32 / fade_len).min(1.0);- let remaining = (self.beep_samples - within) as f32;- let fade_out = (remaining / fade_len).min(1.0);- value =- 0.4 * fade_in * fade_out * (t * 1000.0 * 2.0 * std::f32::consts::PI).sin();-- if within == 0 {- let dac = now- + latency.unwrap_or_default()- + Duration::from_secs_f64(frame_idx as f64 / self.sample_rate as f64);- self.beep_outputs.lock().unwrap().push((event as u32, dac));+ let rel = rel as u64;+ let idx = self+ .event_windows+ .partition_point(|&(start, _)| start <= rel);+ if idx > 0 {+ let (start, end) = self.event_windows[idx - 1];+ if rel < end {+ // 1 kHz tone with a 2 ms fade-in/out to avoid clicks while+ // keeping the onset sharp for detection.+ let within = rel - start;+ let t = within as f32 / self.sample_rate as f32;+ let fade_len = 0.002 * self.sample_rate as f32;+ let fade_in = (within as f32 / fade_len).min(1.0);+ let remaining = (end - rel) as f32;+ let fade_out = (remaining / fade_len).min(1.0);+ value = 0.4+ * fade_in+ * fade_out+ * (t * 1000.0 * 2.0 * std::f32::consts::PI).sin();++ if within == 0 {+ let dac = now+ + latency.unwrap_or_default()+ + Duration::from_secs_f64(+ frame_idx as f64 / self.sample_rate as f64,+ );+ self.beep_outputs+ .lock()+ .unwrap()+ .push(((idx - 1) as u32, dac));+ }}}}@@ -199,11 +224,17 @@ fn build_beep_stream(let sample_rate = config.sample_rate().0;let channels = config.channels() as usize;+ let beep_samples = (spec.flash_len.as_secs_f64() * sample_rate as f64) as u64;let state = Arc::new(BeepState {epoch,- period_samples: (spec.period.as_secs_f64() * sample_rate as f64) as u64,- beep_samples: (spec.flash_len.as_secs_f64() * sample_rate as f64) as u64,- events: spec.events,+ event_windows: spec+ .event_offsets_secs()+ .into_iter()+ .map(|offset| {+ let start = (offset * sample_rate as f64) as u64;+ (start, start + beep_samples)+ })+ .collect(),sample_rate,channels,epoch_sample: Mutex::new(None),@@ -260,6 +291,8 @@ fn build_beep_stream(struct PatternApp {spec: PatternSpec,+ /// Event onsets in seconds from epoch, from `PatternSpec::event_offsets_secs`.+ event_offsets: Vec<f64>,run_start: Instant,epoch: Instant,window: Option<Arc<Window>>,@@ -278,11 +311,12 @@ impl PatternApp {if now < self.epoch {return None;}- let rel = now - self.epoch;- let period = self.spec.period.as_secs_f64();- let event = (rel.as_secs_f64() / period) as u32;- let within = rel.as_secs_f64() - f64::from(event) * period;- (event < self.spec.events && within < self.spec.flash_len.as_secs_f64()).then_some(event)+ let rel = (now - self.epoch).as_secs_f64();+ let flash = self.spec.flash_len.as_secs_f64();+ self.event_offsets+ .iter()+ .position(|&start| rel >= start && rel < start + flash)+ .map(|idx| idx as u32)}fn next_transition(&self, now: Instant) -> Instant {@@ -290,16 +324,18 @@ impl PatternApp {return self.epoch;}let rel = (now - self.epoch).as_secs_f64();- let period = self.spec.period.as_secs_f64();- let event = (rel / period) as u32;- let within = rel - f64::from(event) * period;let flash = self.spec.flash_len.as_secs_f64();- let next_rel = if within < flash {- f64::from(event) * period + flash+ let next_rel = self+ .event_offsets+ .iter()+ .flat_map(|&start| [start, start + flash])+ .filter(|&boundary| boundary > rel)+ .fold(f64::INFINITY, f64::min);+ if next_rel.is_finite() {+ self.epoch + Duration::from_secs_f64(next_rel)} else {- f64::from(event + 1) * period- };- self.epoch + Duration::from_secs_f64(next_rel)+ self.done_at()+ }}fn done_at(&self) -> Instant {@@ -454,6 +490,7 @@ fn run_pattern(spec: PatternSpec) -> Result<PatternReport, String> {.map_err(|e| format!("failed to start audio output: {e}"))?;let mut app = PatternApp {+ event_offsets: spec.event_offsets_secs(),spec,run_start,epoch,diff --git a/apps/cli/src/selftest/playback.rs b/apps/cli/src/selftest/playback.rsnew file mode 100644index 000000000..85261a6ce--- /dev/null+++ b/apps/cli/src/selftest/playback.rs@@ -0,0 +1,838 @@+//! `cap selftest playback` — verifies A/V sync of the editor's playback+//! path: what the renderer presents vs what the audio output plays.+//!+//! The harness opens a flash+beep recording with the real editor machinery+//! (`EditorInstance`: real decoders, real frame scheduling, real audio+//! pipeline) and taps both presentation boundaries — the renderer's frame+//! callback and a headless audio sink that pulls blocks on a device-like+//! real-time schedule. Flash/beep onsets measured in those taps are compared+//! against the same onsets measured in the recording's raw tracks; playback+//! must reproduce the recording's sync within one frame and without drift.+//!+//! Without `--project` the fixture is generated through the real recording+//! pipeline (the same channel-source path the sync matrix uses), so the test+//! runs headless on CI where no capture hardware exists.++use std::{+ path::{Path, PathBuf},+ sync::{Arc, Mutex},+ time::{Duration, Instant},+};++use cap_editor::{EditorFrameOutput, EditorInstance, HEADLESS_CHANNELS, HEADLESS_SAMPLE_RATE};+use cap_project::XY;+use clap::Args;+use serde::Serialize;++use super::measure::{self, SyncMeasurement};++/// Flash/beep schedule of the generated fixture. Mirrors the av-sync pattern:+/// events every two seconds after a settle period, 120 ms flash+beep each.+const FIXTURE_SETTLE_SECS: f64 = 2.0;+const FIXTURE_PERIOD_SECS: f64 = 2.0;+const FIXTURE_FLASH_SECS: f64 = 0.12;+const FIXTURE_TAIL_SECS: f64 = 1.0;+const FIXTURE_FPS: u32 = 30;+const FIXTURE_WIDTH: u32 = 320;+const FIXTURE_HEIGHT: u32 = 240;+/// A video emission gap after the second event: the screen is static, no+/// frames are captured, and playback/export must hold the last frame (the+/// VFR hold path) without disturbing audio sync. Longer than the decoders'+/// FRAME_CACHE_SIZE (90 frames = 3s at 30fps) so the pre-gap hold frame is+/// guaranteed to face cache eviction while requests march through the hole —+/// the regression class where post-gap content got served mid-hold. Events+/// whose flashes fall inside the gap are still beeped; their unpaired beeps+/// are rejected by the measurement's pairing window.+const FIXTURE_GAP_START_SECS: f64 = FIXTURE_SETTLE_SECS + FIXTURE_PERIOD_SECS + 0.4;+const FIXTURE_GAP_LEN_SECS: f64 = 4.2;+/// A second, narrow gap (~30 frames) between the fifth and sixth events.+/// Narrower than the decoders' cache read-ahead window, so it exercises the+/// in-loop narrow-hole answer paths that the long gap's cache-bounds exit+/// never reaches.+const FIXTURE_GAP2_START_SECS: f64 = FIXTURE_SETTLE_SECS + 4.0 * FIXTURE_PERIOD_SECS + 0.4;+const FIXTURE_GAP2_LEN_SECS: f64 = 1.0;++/// The playback-vs-raw delta window is asymmetric because every presentation+/// boundary in the harness shifts it the same way: video content appears at+/// the first playback frame tick at-or-after its pts (0..1 frame late), the+/// renderer adds its render latency, and the zero-latency headless sink+/// consumes audio up to one block before the video clock starts. Audio can+/// therefore legitimately read EARLY by up to a frame plus a block plus a+/// render margin, but reading LATE (or early beyond that window) means the+/// editor's playback mapping itself is off.+const RENDER_MARGIN_MS: f64 = 20.0;+const DELTA_LATE_TOLERANCE_MS: f64 = 15.0;+const PASS_TOTAL_DRIFT_MS: f64 = 40.0;+const PASS_MAD_MS: f64 = 25.0;+/// The export decodes the same tracks offline, so its sync must match the+/// raw recording almost exactly (same budget as the av-sync selftest).+const EXPORT_DELTA_TOLERANCE_MS: f64 = 25.0;+/// Ceiling for waiting on playback to finish beyond the timeline duration.+const PLAYBACK_EXTRA_TIMEOUT: Duration = Duration::from_secs(30);++#[derive(Args)]+pub struct PlaybackArgs {+ /// Existing flash+beep .cap project to measure (defaults to generating a+ /// synthetic fixture through the real recording pipeline)+ #[arg(long)]+ project: Option<PathBuf>,+ /// Seconds of synthetic fixture pattern to generate+ #[arg(long, default_value_t = 20)]+ duration: u64,+ /// Frame rate to drive editor playback at+ #[arg(long, default_value_t = 30)]+ fps: u32,+ /// Skip exporting the project (tests only the playback stage)+ #[arg(long)]+ skip_export: bool,+ /// Keep the generated fixture project on disk for inspection+ #[arg(long)]+ keep: bool,+}++#[derive(Serialize, Clone, Copy, PartialEq, Eq, Debug)]+#[serde(rename_all = "lowercase")]+enum Verdict {+ Pass,+ Fail,+ Inconclusive,+}++#[derive(Serialize)]+struct PlaybackReport {+ verdict: Verdict,+ summary: String,+ /// Sync measured in the recording's raw tracks (ground truth).+ raw: Option<SyncMeasurement>,+ /// Sync measured at the editor playback presentation boundaries.+ playback: Option<SyncMeasurement>,+ /// Sync measured in an export of the same project.+ export: Option<SyncMeasurement>,+ /// playback median offset − raw median offset. Negative = audio early.+ delta_ms: Option<f64>,+ delta_early_tolerance_ms: f64,+ delta_late_tolerance_ms: f64,+ pass_total_drift_ms: f64,+ frames_presented: usize,+ project_path: Option<String>,+}++/// How early audio may legitimately read at the presentation taps: one video+/// frame (content quantization) + one audio block (sink start quantization)+/// + the render margin.+fn delta_early_tolerance_ms(fps: u32) -> f64 {+ 1000.0 / f64::from(fps)+ + 1000.0 * cap_editor::HEADLESS_BLOCK_FRAMES as f64 / f64::from(HEADLESS_SAMPLE_RATE)+ + RENDER_MARGIN_MS+}++pub async fn run_playback(args: PlaybackArgs, json: bool) -> Result<(), String> {+ ffmpeg::util::log::set_level(ffmpeg::util::log::Level::Quiet);++ if !(1..=240).contains(&args.fps) {+ return Err(format!("invalid playback fps: {}", args.fps));+ }++ let progress = |msg: &str| {+ if !json {+ eprintln!("{msg}");+ }+ };++ let (project_path, generated) = match &args.project {+ Some(path) => (path.clone(), false),+ None => {+ let path = std::env::temp_dir().join(format!(+ "cap-selftest-playback-{}.cap",+ uuid::Uuid::new_v4()+ ));+ // The floor guarantees enough events for measure_sync's minimum+ // after the first event is dropped AND the two events whose+ // flashes fall inside the video gap: 18s -> 9 events -> 7 visible+ // -> 6 pairs.+ let pattern_secs = args.duration.clamp(18, 120) as f64;+ progress(&format!(+ "[1/3] Generating synthetic flash+beep recording ({pattern_secs:.0}s, real-time)..."+ ));+ fixture::generate(&path, pattern_secs).await?;+ (path, true)+ }+ };++ progress("[2/3] Measuring the raw recording...");+ let raw = super::analyze_raw(&project_path);++ progress("[3/3] Playing back through the editor and measuring what it presents...");+ let playback = measure_playback(&project_path, args.fps).await;++ // The export drives the same decoders and timeline mapping as playback+ // through the offline path; on CI this is the only place the export-side+ // VFR gap handling is exercised at all.+ let export = if args.skip_export {+ Ok(None)+ } else {+ progress("Exporting and verifying the export...");+ match crate::export::export_project_default(project_path.clone()).await {+ Ok(output) => super::analyze_export(&output).map(Some),+ Err(e) => Err(format!("export failed: {e}")),+ }+ };++ let (verdict, summary, raw_m, playback_m, export_m, delta_ms, frames_presented) =+ evaluate(&args, raw, playback, export);++ let keep = args.keep || (generated && verdict != Verdict::Pass);+ if generated {+ if keep {+ progress(&format!(+ "Fixture project kept at {}",+ project_path.display()+ ));+ } else {+ let _ = std::fs::remove_dir_all(&project_path);+ }+ }++ let report = PlaybackReport {+ verdict,+ summary: summary.clone(),+ raw: raw_m,+ playback: playback_m,+ export: export_m,+ delta_ms,+ delta_early_tolerance_ms: delta_early_tolerance_ms(args.fps),+ delta_late_tolerance_ms: DELTA_LATE_TOLERANCE_MS,+ pass_total_drift_ms: PASS_TOTAL_DRIFT_MS,+ frames_presented,+ project_path: (keep || !generated).then(|| project_path.display().to_string()),+ };++ if json {+ println!(+ "{}",+ serde_json::to_string_pretty(&report)+ .map_err(|e| format!("failed to serialize report: {e}"))?+ );+ } else {+ if let Some(m) = &report.raw {+ println!(+ "\nRecording: offset {:+.0} ms (median), drift {:+.0} ms over {:.0}s, {} events",+ m.median_offset_ms, m.total_drift_ms, m.span_secs, m.inlier_events+ );+ }+ if let Some(m) = &report.playback {+ println!(+ "Playback: offset {:+.0} ms (median), drift {:+.0} ms over {:.0}s, {} events",+ m.median_offset_ms, m.total_drift_ms, m.span_secs, m.inlier_events+ );+ }+ if let Some(m) = &report.export {+ println!(+ "Export: offset {:+.0} ms (median), drift {:+.0} ms over {:.0}s, {} events",+ m.median_offset_ms, m.total_drift_ms, m.span_secs, m.inlier_events+ );+ }+ let label = match verdict {+ Verdict::Pass => "PASS",+ Verdict::Fail => "FAIL",+ Verdict::Inconclusive => "INCONCLUSIVE",+ };+ println!("\nResult: {label} — {summary}");+ }++ match verdict {+ Verdict::Pass => Ok(()),+ Verdict::Fail => Err(format!("editor playback sync check failed: {summary}")),+ Verdict::Inconclusive => Err(format!(+ "editor playback sync check inconclusive: {summary}"+ )),+ }+}++#[allow(clippy::type_complexity)]+fn evaluate(+ args: &PlaybackArgs,+ raw: Result<(SyncMeasurement, f64), String>,+ playback: Result<(SyncMeasurement, usize), String>,+ export: Result<Option<(SyncMeasurement, f64)>, String>,+) -> (+ Verdict,+ String,+ Option<SyncMeasurement>,+ Option<SyncMeasurement>,+ Option<SyncMeasurement>,+ Option<f64>,+ usize,+) {+ let (raw_m, _snr) = match raw {+ Ok(v) => v,+ Err(reason) => {+ return (+ Verdict::Inconclusive,+ format!("could not measure the raw recording: {reason}"),+ None,+ None,+ None,+ None,+ 0,+ );+ }+ };++ let (playback_m, frames_presented) = match playback {+ Ok(v) => v,+ Err(reason) => {+ return (+ Verdict::Fail,+ format!("editor playback could not be measured: {reason}"),+ Some(raw_m),+ None,+ None,+ None,+ 0,+ );+ }+ };++ let export_m = match export {+ Ok(v) => v.map(|(m, _)| m),+ Err(reason) => {+ // A project that plays back but cannot be exported is a hard+ // failure: the export path is part of the product.+ return (+ Verdict::Fail,+ reason,+ Some(raw_m),+ Some(playback_m),+ None,+ None,+ frames_presented,+ );+ }+ };++ let delta = playback_m.median_offset_ms - raw_m.median_offset_ms;+ let early_tolerance = delta_early_tolerance_ms(args.fps);++ let mut reasons = Vec::new();+ if delta < -early_tolerance || delta > DELTA_LATE_TOLERANCE_MS {+ reasons.push(format!(+ "playback shifts sync by {delta:+.0} ms vs the recording \+ (allowed -{early_tolerance:.0}..+{DELTA_LATE_TOLERANCE_MS:.0} ms)"+ ));+ }+ if playback_m.total_drift_ms.abs() > PASS_TOTAL_DRIFT_MS {+ reasons.push(format!(+ "playback accumulates {:+.0} ms of drift over {:.0}s",+ playback_m.total_drift_ms, playback_m.span_secs+ ));+ }+ if playback_m.mad_ms > PASS_MAD_MS {+ reasons.push(format!(+ "playback offsets are unstable (spread ±{:.0} ms)",+ playback_m.mad_ms+ ));+ }+ if let Some(export_m) = &export_m {+ let export_delta = (export_m.median_offset_ms - raw_m.median_offset_ms).abs();+ if export_delta > EXPORT_DELTA_TOLERANCE_MS {+ reasons.push(format!(+ "export changes sync by {export_delta:.0} ms vs the recording"+ ));+ }+ if export_m.total_drift_ms.abs() > PASS_TOTAL_DRIFT_MS {+ reasons.push(format!(+ "export accumulates {:+.0} ms of drift over {:.0}s",+ export_m.total_drift_ms, export_m.span_secs+ ));+ }+ }++ let verdict = if reasons.is_empty() {+ Verdict::Pass+ } else {+ Verdict::Fail+ };+ let summary = if reasons.is_empty() {+ format!(+ "editor playback preserves sync (playback {:+.0} ms vs recording {:+.0} ms, drift {:+.0} ms)",+ playback_m.median_offset_ms, raw_m.median_offset_ms, playback_m.total_drift_ms+ )+ } else {+ reasons.join("; ")+ };++ (+ verdict,+ summary,+ Some(raw_m),+ Some(playback_m),+ export_m,+ Some(delta),+ frames_presented,+ )+}++/// Drives the editor's real playback over the project and measures+/// flash-vs-beep alignment in what it presents. Returns the measurement and+/// the number of frames the renderer actually presented.+async fn measure_playback(+ project_path: &Path,+ fps: u32,+) -> Result<(SyncMeasurement, usize), String> {+ // Wall-clock epoch shared by both presentation taps.+ let epoch = Instant::now();++ let video_events: Arc<Mutex<Vec<(f64, f64)>>> = Arc::new(Mutex::new(Vec::new()));+ let frame_cb: Box<dyn FnMut(EditorFrameOutput) + Send> = Box::new({+ let video_events = video_events.clone();+ move |output| {+ let now = Instant::now();+ if let EditorFrameOutput::Rgba(frame) = output {+ if let Some(luma) = mean_center_luma_rgba(+ &frame.data,+ frame.width,+ frame.height,+ frame.padded_bytes_per_row,+ ) && let Ok(mut events) = video_events.lock()+ {+ events.push((now.duration_since(epoch).as_secs_f64(), luma));+ }+ }+ }+ });++ struct AudioTapState {+ base_secs: Option<f64>,+ mono: Vec<f32>,+ }+ let audio_tap_state = Arc::new(Mutex::new(AudioTapState {+ base_secs: None,+ mono: Vec::new(),+ }));+ let audio_tap: cap_editor::HeadlessAudioTap = Box::new({+ let state = audio_tap_state.clone();+ move |block: &[f32], deadline: Instant| {+ let Ok(mut state) = state.lock() else {+ return;+ };+ if state.base_secs.is_none() {+ // The pump's schedule is absolute, so the first block deadline+ // anchors an exact sample-index -> wall-time mapping.+ state.base_secs = Some(+ deadline+ .checked_duration_since(epoch)+ .map(|d| d.as_secs_f64())+ .unwrap_or_else(|| -epoch.duration_since(deadline).as_secs_f64()),+ );+ }+ for frame in block.chunks_exact(usize::from(HEADLESS_CHANNELS)) {+ state+ .mono+ .push(frame.iter().sum::<f32>() / frame.len() as f32);+ }+ }+ });++ let audio_output = Arc::new(cap_editor::AudioOutput::new_headless(audio_tap));++ let instance = EditorInstance::new_with_audio_output(+ project_path.to_path_buf(),+ |_| {},+ frame_cb,+ None,+ audio_output,+ )+ .await+ .map_err(|e| format!("failed to open the project in the editor: {e}"))?;++ let resolution_base = {+ let display = &instance.recordings.segments[0].display;+ XY::new(display.width, display.height)+ };++ let total_frames = instance.get_total_frames(fps);+ let expected_duration = Duration::from_secs_f64(f64::from(total_frames) / f64::from(fps));++ instance.start_playback(fps, resolution_base).await;++ let mut handle = instance+ .state+ .lock()+ .await+ .playback_task+ .clone()+ .ok_or("editor playback did not start")?;++ let wait = tokio::time::timeout(expected_duration + PLAYBACK_EXTRA_TIMEOUT, async {+ loop {+ let event = *handle.receive_event().await;+ if matches!(event, cap_editor::PlaybackEvent::Stop) {+ break;+ }+ }+ })+ .await;++ instance.dispose().await;++ if wait.is_err() {+ return Err(format!(+ "playback did not finish within {:?}",+ expected_duration + PLAYBACK_EXTRA_TIMEOUT+ ));+ }++ let video_samples = video_events+ .lock()+ .map_err(|_| "video tap poisoned".to_string())?+ .clone();+ let frames_presented = video_samples.len();+ let (audio_base_secs, mono) = {+ let mut state = audio_tap_state+ .lock()+ .map_err(|_| "audio tap poisoned".to_string())?;+ (+ state.base_secs.unwrap_or(0.0),+ std::mem::take(&mut state.mono),+ )+ };++ let flashes = measure::flash_onsets_from_luma(&video_samples)+ .map_err(|e| format!("playback video: {e}"))?;+ let audio = measure::beep_onsets_from_mono(mono, HEADLESS_SAMPLE_RATE)+ .map_err(|e| format!("playback audio: {e}"))?;+ let beeps: Vec<f64> = audio.onsets.iter().map(|t| t + audio_base_secs).collect();++ measure::measure_sync(&flashes, &beeps, super::MIN_EVENTS)+ .map(|m| (m, frames_presented))+ .map_err(|e| format!("playback pairing: {e}"))+}++/// Mean luma over the center crop of an RGBA/BGRA presentation frame.+/// Channel order doesn't matter for the black/white test pattern.+fn mean_center_luma_rgba(+ data: &[u8],+ width: u32,+ height: u32,+ padded_bytes_per_row: u32,+) -> Option<f64> {+ let width = width as usize;+ let height = height as usize;+ let stride = padded_bytes_per_row as usize;+ if width == 0 || height == 0 || stride < width * 4 || data.len() < stride * height {+ return None;+ }++ let x0 = width / 4;+ let x1 = width * 3 / 4;+ let y0 = height / 4;+ let y1 = height * 3 / 4;++ let mut sum = 0u64;+ let mut count = 0u64;+ let mut y = y0;+ while y < y1 {+ let row = &data[y * stride..y * stride + width * 4];+ let mut x = x0;+ while x < x1 {+ let px = &row[x * 4..x * 4 + 3];+ sum += u64::from(px[0]) + u64::from(px[1]) + u64::from(px[2]);+ count += 3;+ x += 4;+ }+ y += 4;+ }+ (count > 0).then(|| sum as f64 / count as f64)+}++/// Generates a real `.cap` studio project containing a flash+beep pattern by+/// driving the production recording pipeline with synthetic sources — the+/// same real-time channel-source path the sync matrix uses. Only the media+/// origin is synthetic; encoding, muxing and metadata are the real product+/// code paths.+mod fixture {+ use std::{path::Path, time::Duration};++ use cap_media_info::{AudioInfo, RawVideoFormat, Sample, Type, VideoInfo};+ use cap_project::{+ AudioMeta, ClipConfiguration, MultipleSegment, MultipleSegments, Platform,+ ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta,+ StudioRecordingStatus, TimelineConfiguration, TimelineSegment, VideoMeta,+ };+ use cap_recording::{+ AudioFrame, ChannelAudioSource, ChannelAudioSourceConfig, ChannelVideoSource,+ ChannelVideoSourceConfig, OutputPipeline,+ ffmpeg::{FFmpegVideoFrame, Mp4Muxer, OggMuxer},+ };+ use cap_timestamp::{Timestamp, Timestamps};+ use relative_path::RelativePathBuf;++ use super::{+ FIXTURE_FLASH_SECS, FIXTURE_FPS, FIXTURE_GAP_LEN_SECS, FIXTURE_GAP_START_SECS,+ FIXTURE_GAP2_LEN_SECS, FIXTURE_GAP2_START_SECS, FIXTURE_HEIGHT, FIXTURE_PERIOD_SECS,+ FIXTURE_SETTLE_SECS, FIXTURE_TAIL_SECS, FIXTURE_WIDTH,+ };++ const AUDIO_RATE: u32 = 48_000;+ const AUDIO_CHUNK_SECS: f64 = 0.02;+ const BEEP_FREQ: f32 = 1_000.0;+ const BEEP_AMPLITUDE: f32 = 0.5;++ struct Pattern {+ events: Vec<f64>,+ total_secs: f64,+ }++ fn pattern(pattern_secs: f64) -> Pattern {+ let events = ((pattern_secs / FIXTURE_PERIOD_SECS) as u32).max(4);+ // Same deterministic anti-aliasing jitter as the live pattern window+ // (PatternSpec::event_offsets_secs): a perfectly periodic schedule+ // would let a one-period A/V shift alias to a zero measured offset.+ let events: Vec<f64> = (0..events)+ .map(|k| {+ let jitter = (u64::from(k).wrapping_mul(2_654_435_761) % 601) as f64 / 1000.0 - 0.3;+ FIXTURE_SETTLE_SECS + (f64::from(k) * FIXTURE_PERIOD_SECS + jitter).max(0.0)+ })+ .collect();+ let total_secs =+ events.last().copied().unwrap_or(0.0) + FIXTURE_FLASH_SECS + FIXTURE_TAIL_SECS;+ Pattern { events, total_secs }+ }++ fn in_flash(events: &[f64], t: f64) -> bool {+ events.iter().any(|&e| t >= e && t < e + FIXTURE_FLASH_SECS)+ }++ fn in_video_gap(t: f64) -> bool {+ (FIXTURE_GAP_START_SECS..FIXTURE_GAP_START_SECS + FIXTURE_GAP_LEN_SECS).contains(&t)+ || (FIXTURE_GAP2_START_SECS..FIXTURE_GAP2_START_SECS + FIXTURE_GAP2_LEN_SECS)+ .contains(&t)+ }++ pub async fn generate(project_dir: &Path, pattern_secs: f64) -> Result<(), String> {+ let pattern = pattern(pattern_secs);++ let segment_dir = project_dir.join("content/segments/segment-0");+ std::fs::create_dir_all(&segment_dir)+ .map_err(|e| format!("failed to create fixture directories: {e}"))?;+ let display_path = segment_dir.join("display.mp4");+ let audio_path = segment_dir.join("system_audio.ogg");++ let timestamps = Timestamps::now();++ // Video leg: black frames with white flashes; nothing is emitted+ // inside the gap window, like a static screen under VFR capture.+ let video_info = VideoInfo::from_raw(+ RawVideoFormat::Bgra,+ FIXTURE_WIDTH,+ FIXTURE_HEIGHT,+ FIXTURE_FPS,+ );+ let (video_tx, video_rx) = flume::bounded::<FFmpegVideoFrame>(32);+ let video_emit = {+ let events = pattern.events.clone();+ let total_secs = pattern.total_secs;+ let base = timestamps.instant();+ tokio::spawn(async move {+ let period = 1.0 / f64::from(FIXTURE_FPS);+ let frame_count = (total_secs * f64::from(FIXTURE_FPS)) as u64;+ for k in 0..frame_count {+ let t = k as f64 * period;+ if in_video_gap(t) {+ continue;+ }+ tokio::time::sleep_until((base + Duration::from_secs_f64(t)).into()).await;+ let mut frame = ffmpeg::frame::Video::new(+ ffmpeg::format::Pixel::BGRA,+ FIXTURE_WIDTH,+ FIXTURE_HEIGHT,+ );+ let shade = if in_flash(&events, t) { 0xFF } else { 0x00 };+ frame.data_mut(0).fill(shade);+ let frame = FFmpegVideoFrame {+ inner: frame,+ timestamp: Timestamp::Instant(base + Duration::from_secs_f64(t)),+ };+ if video_tx.send_async(frame).await.is_err() {+ break;+ }+ }+ })+ };++ // Audio leg: silence with 1 kHz beep bursts aligned to the flashes.+ let audio_info = AudioInfo::new(Sample::F32(Type::Packed), AUDIO_RATE, 2)+ .map_err(|e| format!("audio info: {e:?}"))?;+ let (audio_tx, audio_rx) = futures::channel::mpsc::channel::<AudioFrame>(32);+ let audio_emit = {+ let events = pattern.events.clone();+ let total_secs = pattern.total_secs;+ let base = timestamps.instant();+ let mut tx = audio_tx;+ let info = audio_info;+ tokio::spawn(async move {+ use futures::SinkExt;+ let chunk_frames = (f64::from(AUDIO_RATE) * AUDIO_CHUNK_SECS) as usize;+ let total_chunks = (total_secs / AUDIO_CHUNK_SECS).ceil() as usize;+ for k in 0..total_chunks {+ let chunk_t = k as f64 * AUDIO_CHUNK_SECS;+ tokio::time::sleep_until((base + Duration::from_secs_f64(chunk_t)).into())+ .await;+ let mut frame = ffmpeg::frame::Audio::new(+ ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),+ chunk_frames,+ info.channel_layout(),+ );+ frame.set_rate(AUDIO_RATE);+ let data = frame.data_mut(0);+ let samples = unsafe {+ std::slice::from_raw_parts_mut(+ data.as_mut_ptr().cast::<f32>(),+ data.len() / 4,+ )+ };+ for (i, sample) in samples.iter_mut().enumerate() {+ let n = (k * chunk_frames + i / 2) as f64;+ let t = n / f64::from(AUDIO_RATE);+ *sample = if in_flash(&events, t) {+ (t as f32 * BEEP_FREQ * 2.0 * std::f32::consts::PI).sin()+ * BEEP_AMPLITUDE+ } else {+ 0.0+ };+ }+ let frame = AudioFrame::new(+ frame,+ Timestamp::Instant(base + Duration::from_secs_f64(chunk_t)),+ );+ if tx.send(frame).await.is_err() {+ break;+ }+ }+ })+ };++ let video_pipeline = OutputPipeline::builder(display_path.clone())+ .with_video::<ChannelVideoSource<FFmpegVideoFrame>>(ChannelVideoSourceConfig::new(+ video_info, video_rx,+ ))+ .with_timestamps(timestamps)+ .build::<Mp4Muxer>(())+ .await+ .map_err(|e| format!("video pipeline: {e}"))?;+ let audio_pipeline = OutputPipeline::builder(audio_path.clone())+ .with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(+ audio_info, audio_rx,+ ))+ .with_timestamps(timestamps)+ .build::<OggMuxer>(())+ .await+ .map_err(|e| format!("audio pipeline: {e}"))?;++ video_emit+ .await+ .map_err(|e| format!("video emit join: {e}"))?;+ audio_emit+ .await+ .map_err(|e| format!("audio emit join: {e}"))?;+ // Let the stream tails flush through the encoders.+ tokio::time::sleep(Duration::from_millis(500)).await;++ let finished_video = video_pipeline+ .stop()+ .await+ .map_err(|e| format!("video pipeline stop: {e}"))?;+ let finished_audio = audio_pipeline+ .stop()+ .await+ .map_err(|e| format!("audio pipeline stop: {e}"))?;++ // Persist metadata the way the studio recorder does: start times are+ // each track's first timestamp on the shared clock, and the timeline+ // covers the real muxed video span.+ let display_start = finished_video+ .first_timestamp+ .signed_duration_since_secs(timestamps);+ let audio_start = finished_audio+ .first_timestamp+ .signed_duration_since_secs(timestamps);+ let display_duration = finished_video+ .video_timestamp_span+ .map(|(first, last)| (last - first).as_secs_f64() + 1.0 / f64::from(FIXTURE_FPS))+ .ok_or("fixture video reported no timestamp span")?;++ let meta = StudioRecordingMeta::MultipleSegments {+ inner: MultipleSegments {+ segments: vec![MultipleSegment {+ display: VideoMeta {+ path: RelativePathBuf::from("content/segments/segment-0/display.mp4"),+ fps: FIXTURE_FPS,+ start_time: Some(display_start),+ device_id: None,+ },+ camera: None,+ mic: None,+ system_audio: Some(AudioMeta {+ path: RelativePathBuf::from("content/segments/segment-0/system_audio.ogg"),+ start_time: Some(audio_start),+ device_id: None,+ gap_summary: finished_audio.audio_gap_summary.map(|s| {+ cap_project::AudioGapSummary {+ total_overlap_trimmed_ms: s.total_overlap_trimmed_ms,+ startup_overlap_trimmed_ms: s.startup_overlap_trimmed_ms,+ overlap_dropped_frames: s.overlap_dropped_frames,+ startup_overlap_drops: s.startup_overlap_drops,+ }+ }),+ }),+ cursor: None,+ keyboard: None,+ }],+ cursors: Default::default(),+ status: Some(StudioRecordingStatus::Complete),+ },+ };++ let recording_meta = RecordingMeta {+ platform: Some(Platform::default()),+ project_path: project_dir.to_path_buf(),+ pretty_name: "Cap Playback Selftest Fixture".to_string(),+ sharing: None,+ inner: RecordingMetaInner::Studio(Box::new(meta)),+ upload: None,+ };+ recording_meta+ .save_for_project()+ .map_err(|e| format!("failed to write recording meta: {e:?}"))?;++ let project_config = ProjectConfiguration {+ timeline: Some(TimelineConfiguration {+ segments: vec![TimelineSegment {+ recording_clip: 0,+ start: 0.0,+ end: display_duration,+ timescale: 1.0,+ name: None,+ }],+ zoom_segments: Vec::new(),+ scene_segments: Vec::new(),+ mask_segments: Vec::new(),+ text_segments: Vec::new(),+ caption_segments: Vec::new(),+ keyboard_segments: Vec::new(),+ audio_segments: Vec::new(),+ }),+ clips: vec![ClipConfiguration {+ index: 0,+ offsets: Default::default(),+ }],+ ..Default::default()+ };+ project_config+ .write(project_dir)+ .map_err(|e| format!("failed to write project config: {e}"))?;++ Ok(())+ }+}diff --git a/crates/editor/src/audio_output.rs b/crates/editor/src/audio_output.rsindex 080ffdc03..655003ecb 100644--- a/crates/editor/src/audio_output.rs+++ b/crates/editor/src/audio_output.rs@@ -13,10 +13,10 @@ use std::{atomic::{AtomicBool, AtomicU64, Ordering},mpsc as std_mpsc,},- time::Duration,+ time::{Duration, Instant},};-use cap_audio::FromSampleBytes;+use cap_audio::{AudioData, FromSampleBytes};#[cfg(not(target_os = "windows"))]use cap_audio::{LatencyCorrectionConfig, LatencyCorrector, default_output_latency_hint};use cap_media_info::AudioInfo;@@ -77,6 +77,18 @@ impl Default for AudioOutput {}}+/// Sample rate of the headless sink; matches the pipeline's master clock.+pub const HEADLESS_SAMPLE_RATE: u32 = 48_000;+/// Channel count of the headless sink.+pub const HEADLESS_CHANNELS: u16 = 2;+/// Frames per pulled block in the headless sink (a typical device period).+pub const HEADLESS_BLOCK_FRAMES: usize = 512;++/// Receives every interleaved f32 block the headless sink pulls, together+/// with the deadline at which a real output device would start playing the+/// block's first sample.+pub type HeadlessAudioTap = Box<dyn FnMut(&[f32], Instant) + Send>;+impl AudioOutput {pub fn new() -> Self {let (control_tx, control_rx) = std_mpsc::channel();@@ -96,6 +108,27 @@ impl AudioOutput {}}+ /// An output that renders into `tap` instead of a device, pulling blocks+ /// on a real-time schedule the way a sound card would. Runs the exact+ /// production source pipeline (pre-render buffer, playhead sync policy),+ /// so sync harnesses can observe what a device would have played without+ /// needing audio hardware.+ pub fn new_headless(tap: HeadlessAudioTap) -> Self {+ let (control_tx, control_rx) = std_mpsc::channel();++ if let Err(e) = std::thread::Builder::new()+ .name("cap-audio-headless".into())+ .spawn(move || control_thread_headless(control_rx, tap))+ {+ error!("Failed to spawn headless audio output thread: {e}");+ }++ Self {+ control_tx,+ next_generation: AtomicU64::new(0),+ }+ }+/// Opens the output stream ahead of the first play so even the first/// press doesn't wait on the device (Bluetooth wake, etc.). Non-blocking.pub fn prewarm(&self) {@@ -210,6 +243,239 @@ fn control_thread(control_rx: std_mpsc::Receiver<ControlMsg>) {info!("Audio output thread finished");}+/// Applies pending install/remove commands to the active source. Shared by+/// the live cpal callback and the headless sink.+fn drain_source_commands<T: FromSampleBytes>(+ active: &mut Option<ActiveSource<T>>,+ source_rx: &std_mpsc::Receiver<SourceCommand<T>>,+) {+ while let Ok(command) = source_rx.try_recv() {+ match command {+ SourceCommand::Install(source) => *active = Some(*source),+ SourceCommand::Remove { generation } => {+ let matches = generation.is_none()+ || active+ .as_ref()+ .map(|s| Some(s.generation) == generation)+ .unwrap_or(false);+ if matches {+ *active = None;+ }+ }+ }+ }+}++/// Renders one output block from the active source: applies the video+/// playhead sync policy, fills the buffer and acknowledges the first+/// consumed block. Shared by the live cpal callback and the headless sink so+/// harnesses exercise the exact production logic.+fn render_source_block<T: FromSampleBytes + cpal::FromSample<f32>>(+ source: &mut ActiveSource<T>,+ buffer: &mut [T],+ latency_secs: f64,+) {+ if source.playhead_rx.has_changed().unwrap_or(false) {+ let video_playhead = *source.playhead_rx.borrow_and_update();+ let jump = (video_playhead - source.last_video_playhead).abs();+ let audible_playhead = source.buffer.current_audible_playhead(latency_secs);+ let drift = (video_playhead - audible_playhead).abs();++ if jump > 0.05 || drift > 0.04 {+ source.buffer.set_playhead(video_playhead + latency_secs);+ }++ source.last_video_playhead = video_playhead;+ }++ source.buffer.fill(buffer);++ if let Some(ack) = source.ack.take() {+ let _ = ack.send(());+ }+}++/// Builds the per-playback source from a play spec and hands it to the+/// output via `install_tx`. `use_device_latency_hint` is false for the+/// headless sink, which models a zero-latency device.+fn install_source<T: FromSampleBytes + cpal::FromSample<f32>>(+ spec: Box<PlaySpec>,+ generation: u64,+ ack: std_mpsc::Sender<()>,+ output_info: AudioInfo,+ use_device_latency_hint: bool,+ install_tx: &std_mpsc::Sender<SourceCommand<T>>,+) -> Result<(), String> {+ let PlaySpec {+ segments,+ music,+ project,+ duration_secs,+ start_playhead_secs,+ playhead_rx,+ } = *spec;++ if !(duration_secs.is_finite() && duration_secs > 0.0) {+ return Err(format!(+ "Invalid audio pre-render duration: {duration_secs}"+ ));+ }++ #[cfg(not(target_os = "windows"))]+ let latency_corrector = {+ let hint = if use_device_latency_hint {+ default_output_latency_hint(output_info.sample_rate, output_info.buffer_size)+ } else {+ None+ };+ if let Some(hint) = hint+ && hint.latency_secs > 0.0+ {+ if hint.transport.is_wireless() {+ info!(+ "Applying wireless audio output latency hint: {:.1} ms",+ hint.latency_secs * 1_000.0+ );+ } else {+ info!(+ "Applying audio output latency hint: {:.1} ms",+ hint.latency_secs * 1_000.0+ );+ }+ }+ LatencyCorrector::new(hint, LatencyCorrectionConfig::default())+ };+ #[cfg(not(target_os = "windows"))]+ let initial_latency_secs = latency_corrector.initial_output_latency_secs();+ #[cfg(target_os = "windows")]+ let initial_latency_secs = {+ let _ = use_device_latency_hint;+ 0.0+ };++ let start_playhead = start_playhead_secs + initial_latency_secs;+ let mut buffer = PrerenderedAudioBuffer::<T>::new(+ segments,+ music,+ &project,+ output_info,+ duration_secs,+ start_playhead,+ );+ buffer.set_playhead(start_playhead);+ // A few ms: guarantees the callback reads real samples at the+ // playhead, never leading silence.+ buffer.wait_until_ready(PRERENDER_READY_TIMEOUT);++ install_tx+ .send(SourceCommand::Install(Box::new(ActiveSource {+ generation,+ buffer,+ playhead_rx,+ last_video_playhead: start_playhead_secs,+ ack: Some(ack),+ #[cfg(not(target_os = "windows"))]+ latency_corrector,+ })))+ .map_err(|_| "Audio callback channel closed".to_string())+}++/// Control loop for the headless sink: a pump thread pulls blocks on a+/// real-time schedule (as a device would) and hands every block to `tap`.+fn control_thread_headless(control_rx: std_mpsc::Receiver<ControlMsg>, mut tap: HeadlessAudioTap) {+ let output_info = AudioInfo::new_raw(+ AudioData::SAMPLE_FORMAT,+ HEADLESS_SAMPLE_RATE,+ HEADLESS_CHANNELS,+ );++ let (source_tx, source_rx) = std_mpsc::channel::<SourceCommand<f32>>();+ let stop = Arc::new(AtomicBool::new(false));++ let pump = {+ let stop = stop.clone();+ let channels = usize::from(HEADLESS_CHANNELS);+ std::thread::Builder::new()+ .name("cap-audio-headless-pump".into())+ .spawn(move || {+ let mut buffer = vec![0.0f32; HEADLESS_BLOCK_FRAMES * channels];+ let mut active: Option<ActiveSource<f32>> = None;+ let block = Duration::from_secs_f64(+ HEADLESS_BLOCK_FRAMES as f64 / f64::from(HEADLESS_SAMPLE_RATE),+ );+ let start = Instant::now();+ let mut n: u32 = 0;++ while !stop.load(Ordering::Acquire) {+ // Absolute schedule: a device consumes samples isochronously,+ // so late wakeups must not stretch the sample clock.+ let deadline = start + block * n;+ let now = Instant::now();+ if deadline > now {+ std::thread::sleep(deadline - now);+ }++ drain_source_commands(&mut active, &source_rx);+ match active.as_mut() {+ Some(source) => render_source_block(source, &mut buffer, 0.0),+ None => buffer.fill(0.0),+ }+ tap(&buffer, deadline);+ n = n.saturating_add(1);+ }+ })+ };+ let pump = match pump {+ Ok(handle) => Some(handle),+ Err(e) => {+ error!("Failed to spawn headless audio pump: {e}");+ None+ }+ };++ while let Ok(msg) = control_rx.recv() {+ match msg {+ ControlMsg::EnsureStream => {}+ ControlMsg::Play {+ spec,+ generation,+ result_tx,+ } => {+ let (ack_tx, ack_rx) = std_mpsc::channel();+ let ok = pump.is_some()+ && match install_source::<f32>(+ spec,+ generation,+ ack_tx,+ output_info,+ false,+ &source_tx,+ ) {+ Ok(()) => ack_rx.recv_timeout(SOURCE_ACK_TIMEOUT).is_ok(),+ Err(e) => {+ error!("Failed to install headless audio source: {e}");+ false+ }+ };+ let _ = result_tx.send(ok);+ }+ ControlMsg::StopPlayback { generation } => {+ let _ = source_tx.send(SourceCommand::Remove {+ generation: Some(generation),+ });+ }+ ControlMsg::Shutdown => break,+ }+ }++ stop.store(true, Ordering::Release);+ if let Some(pump) = pump {+ let _ = pump.join();+ }++ info!("Headless audio output thread finished");+}+fn handle_play(state: &mut Option<StreamState>, spec: Box<PlaySpec>, generation: u64) -> bool {if !ensure_stream(state) {return false;@@ -318,21 +584,7 @@ where.build_output_stream(&config,move |buffer: &mut [T], info| {- while let Ok(command) = source_rx.try_recv() {- match command {- SourceCommand::Install(source) => active = Some(*source),- SourceCommand::Remove { generation } => {- let matches = generation.is_none()- || active- .as_ref()- .map(|s| Some(s.generation) == generation)- .unwrap_or(false);- if matches {- active = None;- }- }- }- }+ drain_source_commands(&mut active, &source_rx);let Some(source) = active.as_mut() else {buffer.fill(T::EQUILIBRIUM);@@ -347,24 +599,7 @@ where0.0};- if source.playhead_rx.has_changed().unwrap_or(false) {- let video_playhead = *source.playhead_rx.borrow_and_update();- let jump = (video_playhead - source.last_video_playhead).abs();- let audible_playhead = source.buffer.current_audible_playhead(latency_secs);- let drift = (video_playhead - audible_playhead).abs();-- if jump > 0.05 || drift > 0.04 {- source.buffer.set_playhead(video_playhead + latency_secs);- }-- source.last_video_playhead = video_playhead;- }-- source.buffer.fill(buffer);-- if let Some(ack) = source.ack.take() {- let _ = ack.send(());- }+ render_source_block(source, buffer, latency_secs);},{let failed = failed.clone();@@ -384,72 +619,7 @@ wherelet install_tx = source_tx.clone();let install = Box::new(move |spec: Box<PlaySpec>, generation: u64, ack: std_mpsc::Sender<()>| {- let PlaySpec {- segments,- music,- project,- duration_secs,- start_playhead_secs,- playhead_rx,- } = *spec;-- if !(duration_secs.is_finite() && duration_secs > 0.0) {- return Err(format!(- "Invalid audio pre-render duration: {duration_secs}"- ));- }-- #[cfg(not(target_os = "windows"))]- let latency_corrector = {- let hint =- default_output_latency_hint(output_info.sample_rate, output_info.buffer_size);- if let Some(hint) = hint- && hint.latency_secs > 0.0- {- if hint.transport.is_wireless() {- info!(- "Applying wireless audio output latency hint: {:.1} ms",- hint.latency_secs * 1_000.0- );- } else {- info!(- "Applying audio output latency hint: {:.1} ms",- hint.latency_secs * 1_000.0- );- }- }- LatencyCorrector::new(hint, LatencyCorrectionConfig::default())- };- #[cfg(not(target_os = "windows"))]- let initial_latency_secs = latency_corrector.initial_output_latency_secs();- #[cfg(target_os = "windows")]- let initial_latency_secs = 0.0;-- let start_playhead = start_playhead_secs + initial_latency_secs;- let mut buffer = PrerenderedAudioBuffer::<T>::new(- segments,- music,- &project,- output_info,- duration_secs,- start_playhead,- );- buffer.set_playhead(start_playhead);- // A few ms: guarantees the callback reads real samples at the- // playhead, never leading silence.- buffer.wait_until_ready(PRERENDER_READY_TIMEOUT);-- install_tx- .send(SourceCommand::Install(Box::new(ActiveSource {- generation,- buffer,- playhead_rx,- last_video_playhead: start_playhead_secs,- ack: Some(ack),- #[cfg(not(target_os = "windows"))]- latency_corrector,- })))- .map_err(|_| "Audio callback channel closed".to_string())+ install_source::<T>(spec, generation, ack, output_info, true, &install_tx)},);diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 5ef4e0a83..22dca55f7 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -115,6 +115,26 @@ impl EditorInstance {on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,frame_cb: Box<dyn FnMut(editor::EditorFrameOutput) + Send>,shared_device: Option<SharedWgpuDevice>,+ ) -> Result<Arc<Self>, String> {+ Self::new_with_audio_output(+ project_path,+ on_state_change,+ frame_cb,+ shared_device,+ Arc::new(crate::AudioOutput::new()),+ )+ .await+ }++ /// Like [`EditorInstance::new`] but with a caller-provided audio output,+ /// letting harnesses substitute a headless sink while everything else+ /// (decoders, renderer, playback) runs the production path.+ pub async fn new_with_audio_output(+ project_path: PathBuf,+ on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,+ frame_cb: Box<dyn FnMut(editor::EditorFrameOutput) + Send>,+ shared_device: Option<SharedWgpuDevice>,+ audio_output: Arc<crate::AudioOutput>,) -> Result<Arc<Self>, String> {if !project_path.exists() {return Err(format!("Video path {} not found!", project_path.display()));@@ -260,7 +280,6 @@ impl EditorInstance {// Open the session's audio output stream now (in the background) so// the first play press doesn't wait on the device — Bluetooth outputs// in particular can take seconds to wake.- let audio_output = Arc::new(crate::AudioOutput::new());let has_declared_audio = match meta.as_ref() {StudioRecordingMeta::SingleSegment { segment } => segment.audio.is_some(),StudioRecordingMeta::MultipleSegments { inner } => innerdiff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rsindex 1c4d2fd3b..6b4dfd1bd 100644--- a/crates/editor/src/lib.rs+++ b/crates/editor/src/lib.rs@@ -7,7 +7,9 @@ mod segments;mod telemetry;pub use audio::{AudioRenderer, MusicTracks};-pub use audio_output::AudioOutput;+pub use audio_output::{+ AudioOutput, HEADLESS_BLOCK_FRAMES, HEADLESS_CHANNELS, HEADLESS_SAMPLE_RATE, HeadlessAudioTap,+};pub use editor::{EditorFrameOutput, Renderer, RendererHandle, finish_renderer_layers_creation,start_renderer_layers_creation,