Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(verify): Instant recordings through the real Instant muxers with an output oracle

Richie McIlroy6906282dd76c
diff --git a/crates/verify/expectations.toml b/crates/verify/expectations.toml
index 699dfc501..1a6b7da09 100644
--- a/crates/verify/expectations.toml
+++ b/crates/verify/expectations.toml
@@ -102,3 +102,47 @@ case = "seek/*/storm*/ffmpeg"
class = "stale"
reason = "NEW: FFmpeg decoder seeks answer stale frames: the backward-seek lookback tolerance serves a cached frame 1-4 source frames old, and seeks near the start show frame 0 (up to 67 source frames stale)"
link = ""
+
+# Instant mode (fixtures recorded through the real Instant muxers and
+# finalize_instant_output). Needs confirmation with real capture devices
+# (recording track); the product anchors the Instant audio track at the
+# recording epoch on Linux only.
+
+[[xfail]]
+case = "export/instant-ungated-mic-late/output/mp4/native"
+class = "sync"
+platforms = ["macos", "windows"]
+reason = "NEW: the Instant audio track is anchored at its first sample (AudioAnchor::FirstFrame) and nothing aligns it to the screen afterwards: a mic that becomes ready 0.2 s after the screen plays 200 ms early in output.mp4"
+link = ""
+
+[[xfail]]
+case = "export/instant-ungated-system-loopback/output/mp4/native"
+class = "sync"
+platforms = ["macos", "windows"]
+reason = "NEW: same anchor, loopback-style system audio (WASAPI delivers packets only while sound plays): the first sound becomes audio zero, so all audio is early by the time to first sound (260 ms here)"
+link = ""
+
+[[xfail]]
+case = "export/instant-gated-*/output/mp4/native"
+class = "sync"
+reason = "NEW: after the start gate opens, the screen and audio pipelines each take their own first admitted frame as zero, so audio is late by up to one video frame (13 ms with the gate opening between frames; 30-33 ms when it opens on a frame)"
+link = ""
+
+[[xfail]]
+case = "export/instant-gated-system-only/output/mp4/native"
+class = "audio"
+flaky = true
+reason = "NEW: gated loopback-only system audio sometimes loses markers (2 of 11 lost in 1 of 2 fresh recordings, with the track 958 ms early)"
+link = ""
+
+[[xfail]]
+case = "export/instant/output/mp4/native"
+class = "audio"
+reason = "NEW: mic plus loopback system audio mixed into the Instant audio track behind the start gate: every system-audio marker is missing from output.mp4 (11 of 11, 3 of 3 recordings)"
+link = ""
+
+[[xfail]]
+case = "export/instant/output/mp4/native"
+class = "sync"
+reason = "NEW: see instant-gated-*: audio up to one frame late after the start gate"
+link = ""
diff --git a/crates/verify/src/catalog.rs b/crates/verify/src/catalog.rs
index 054847109..429e204fe 100644
--- a/crates/verify/src/catalog.rs
+++ b/crates/verify/src/catalog.rs
@@ -269,3 +269,68 @@ pub fn recorded_studio(_tier: Tier) -> crate::pipeline::RecordedSpec {
],
}
}
+
+/// Instant recording through the real Instant muxers, started like the app
+/// does (sources warm up, then the start gate opens at 0.517 s, between two frames): steady 30 fps
+/// screen with a static hold, a mic that becomes ready at 0.2 s,
+/// loopback-style system audio.
+pub fn recorded_instant(_tier: Tier) -> crate::pipeline::InstantSpec {
+ use crate::pipeline::{Delivery, InstantSpec, RecordedVideo};
+ InstantSpec {
+ name: "instant".into(),
+ duration: 6.0,
+ screen: RecordedVideo {
+ width: SCREEN_W,
+ height: SCREEN_H,
+ fps: 30,
+ delivery: Delivery::Holds(vec![(2.5, 1.2)]),
+ start_delay: 0.0,
+ },
+ mic_delay: Some(0.2),
+ system_audio: true,
+ system_continuous: false,
+ arm_at: Some(0.517),
+ }
+}
+
+/// Instant variants isolating each audio source's start behaviour: no start
+/// gate, so a source that delivers its first sample after the screen does.
+pub fn instant_variants(tier: Tier) -> Vec<crate::pipeline::InstantSpec> {
+ let base = recorded_instant(tier);
+ vec![
+ crate::pipeline::InstantSpec {
+ name: "instant-ungated-mic-late".into(),
+ system_audio: false,
+ arm_at: None,
+ ..base.clone()
+ },
+ crate::pipeline::InstantSpec {
+ name: "instant-ungated-system-loopback".into(),
+ mic_delay: None,
+ arm_at: None,
+ ..base.clone()
+ },
+ crate::pipeline::InstantSpec {
+ name: "instant-ungated-system-continuous-mic-late".into(),
+ system_continuous: true,
+ arm_at: None,
+ ..base.clone()
+ },
+ crate::pipeline::InstantSpec {
+ name: "instant-gated-system-only".into(),
+ mic_delay: None,
+ ..base.clone()
+ },
+ crate::pipeline::InstantSpec {
+ name: "instant-gated-system-continuous-mic-late".into(),
+ system_continuous: true,
+ ..base.clone()
+ },
+ crate::pipeline::InstantSpec {
+ name: "instant-gated-mic-only".into(),
+ system_audio: false,
+ ..base.clone()
+ },
+ base,
+ ]
+}
diff --git a/crates/verify/src/fixture.rs b/crates/verify/src/fixture.rs
index 9c18df40c..de6ac9197 100644
--- a/crates/verify/src/fixture.rs
+++ b/crates/verify/src/fixture.rs
@@ -29,7 +29,7 @@ use crate::{
};
/// Bump when generated output changes so cached fixtures are rebuilt.
-pub const GENERATOR_VERSION: u32 = 1;
+pub const GENERATOR_VERSION: u32 = 2;
/// splitmix64: tiny deterministic PRNG; every fixture prints its seed.
#[derive(Clone)]
diff --git a/crates/verify/src/pipeline.rs b/crates/verify/src/pipeline.rs
index f95905a2d..456fbb899 100644
--- a/crates/verify/src/pipeline.rs
+++ b/crates/verify/src/pipeline.rs
@@ -419,3 +419,276 @@ pub async fn record_studio(spec: &RecordedSpec, dir: &Path) -> anyhow::Result<()
write_project_files(dir, &spec.name, segments)?;
Ok(())
}
+
+/// An Instant recording: segmented screen video and one mixed audio track
+/// (microphone and system audio) through the Instant muxers, finalised into
+/// `content/output.mp4` by the product's `finalize_instant_output`.
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct InstantSpec {
+ pub name: String,
+ pub duration: f64,
+ pub screen: RecordedVideo,
+ pub mic_delay: Option<f64>,
+ pub system_audio: bool,
+ /// System audio delivered continuously from the start (macOS capture)
+ /// instead of loopback-style packets only while a marker plays.
+ #[serde(default)]
+ pub system_continuous: bool,
+ /// Arm a recording start gate this many seconds after the sources start
+ /// (the app's start cue); `None` records from the first frame.
+ #[serde(default)]
+ pub arm_at: Option<f64>,
+}
+
+impl InstantSpec {
+ pub fn cache_key(&self) -> String {
+ crate::fixture::cache_key(&format!("instant-{}", self.name), self)
+ }
+}
+
+/// Where each marker was emitted, on the recording clock (seconds after the
+/// pipeline epoch). Written next to the project as `verify-emitted.json`.
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+pub struct Emitted {
+ /// (slot, emit time) of every screen frame.
+ pub screen: Vec<(u32, f64)>,
+ pub fps: u32,
+ /// (source, marker index, chirp time) of every audio marker.
+ pub audio: Vec<(AudioSource, u32, f64)>,
+}
+
+pub async fn record_instant(spec: &InstantSpec, dir: &Path) -> anyhow::Result<()> {
+ use cap_recording::{DashSegmentedAudioMuxer, DashSegmentedAudioMuxerConfig};
+ crate::media::init();
+ if dir.exists() {
+ std::fs::remove_dir_all(dir)?;
+ }
+ let content = dir.join("content");
+ std::fs::create_dir_all(&content)?;
+ let timestamps = Timestamps::now();
+ let base = timestamps.instant();
+ let gate = spec
+ .arm_at
+ .map(|_| cap_recording::RecordingStartGate::new());
+ let mut emitted = Emitted {
+ fps: spec.screen.fps,
+ ..Default::default()
+ };
+
+ let video = &spec.screen;
+ let info = VideoInfo::from_raw(RawVideoFormat::Bgra, video.width, video.height, video.fps);
+ let (tx, rx) = flume::bounded::<FFmpegVideoFrame>(32);
+ let slots = video
+ .delivery
+ .slots(video.fps, spec.duration - video.start_delay);
+ for &slot in &slots {
+ emitted.screen.push((
+ slot,
+ video.start_delay + f64::from(slot) / f64::from(video.fps),
+ ));
+ }
+ let (fps, width, height, delay) = (video.fps, video.width, video.height, video.start_delay);
+ let video_emit = tokio::spawn(async move {
+ for slot in slots {
+ let t = delay + f64::from(slot) / f64::from(fps);
+ let at = base + Duration::from_secs_f64(t);
+ tokio::time::sleep_until(at.into()).await;
+ let frame = FFmpegVideoFrame {
+ inner: bgra_frame(FrameMarker::new(StreamKind::Screen, 0, slot), width, height),
+ timestamp: Timestamp::Instant(at),
+ };
+ if tx.send_async(frame).await.is_err() {
+ break;
+ }
+ }
+ });
+ let mut video_builder = OutputPipeline::builder(content.join("display"))
+ .with_video::<ChannelVideoSource<FFmpegVideoFrame>>(ChannelVideoSourceConfig::new(info, rx))
+ .with_timestamps(timestamps);
+ if let Some(gate) = &gate {
+ video_builder = video_builder.with_start_gate(Some(gate.clone()));
+ }
+ let video_pipeline = video_builder
+ .build::<cap_recording::ffmpeg::SegmentedVideoMuxer>(
+ cap_recording::ffmpeg::SegmentedVideoMuxerConfig {
+ segment_duration: Duration::from_secs(2),
+ ..Default::default()
+ },
+ )
+ .await
+ .map_err(|e| anyhow!("instant video pipeline: {e}"))?;
+
+ let mono_info = AudioInfo::new(Sample::F32(Type::Packed), AUDIO_RATE, 1)
+ .map_err(|e| anyhow!("audio info: {e:?}"))?;
+ let stereo_info = AudioInfo::new(Sample::F32(Type::Packed), AUDIO_RATE, 2)
+ .map_err(|e| anyhow!("audio info: {e:?}"))?;
+ let mut audio_emits: Vec<AudioEmit> = Vec::new();
+ let mut builder = OutputPipeline::builder(content.join("audio")).with_timestamps(timestamps);
+ if let Some(gate) = &gate {
+ builder = builder.with_start_gate(Some(gate.clone()));
+ }
+ // Mirrors the product's Instant audio pipeline, which anchors at the
+ // recording epoch on Linux only.
+ if cfg!(target_os = "linux") {
+ builder = builder.with_audio_anchor(cap_recording::AudioAnchor::PipelineEpoch);
+ }
+ let has_audio = spec.mic_delay.is_some() || spec.system_audio;
+ if spec.system_audio {
+ let track = marker_track(AudioSource::System, spec.duration);
+ let schedule =
+ audio_code::standard_schedule(AudioSource::System, 0.1, spec.duration - 0.1, 0.5);
+ emitted.audio.extend(
+ schedule
+ .iter()
+ .map(|p| (AudioSource::System, p.index, p.time_secs)),
+ );
+ let (mut tx, rx) = futures::channel::mpsc::channel::<AudioFrame>(32);
+ let continuous = spec.system_continuous;
+ let duration = spec.duration;
+ audio_emits.push(tokio::spawn(async move {
+ use futures::SinkExt;
+ if continuous {
+ for k in 0..(duration / AUDIO_CHUNK_SECS) as usize {
+ let t = k as f64 * AUDIO_CHUNK_SECS;
+ let at = base + Duration::from_secs_f64(t);
+ tokio::time::sleep_until(at.into()).await;
+ let frame = AudioFrame::new(
+ audio_chunk(&track, t, &stereo_info),
+ Timestamp::Instant(at),
+ );
+ if tx.send(frame).await.is_err() {
+ break;
+ }
+ }
+ return tx;
+ }
+ for placement in schedule {
+ let first = (placement.time_secs / AUDIO_CHUNK_SECS).floor() as usize;
+ let last = ((placement.time_secs + audio_code::MARKER_SECS) / AUDIO_CHUNK_SECS)
+ .ceil() as usize;
+ for k in first..last {
+ let t = k as f64 * AUDIO_CHUNK_SECS;
+ let at = base + Duration::from_secs_f64(t);
+ tokio::time::sleep_until(at.into()).await;
+ let frame = AudioFrame::new(
+ audio_chunk(&track, t, &stereo_info),
+ Timestamp::Instant(at),
+ );
+ if tx.send(frame).await.is_err() {
+ return tx;
+ }
+ }
+ }
+ tx
+ }));
+ builder = builder.with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(
+ stereo_info,
+ rx,
+ ));
+ }
+ if let Some(delay) = spec.mic_delay {
+ let track = marker_track(AudioSource::Mic, spec.duration);
+ let schedule =
+ audio_code::standard_schedule(AudioSource::Mic, 0.1, spec.duration - 0.1, 0.5);
+ emitted.audio.extend(
+ schedule
+ .iter()
+ .filter(|p| p.time_secs >= delay)
+ .map(|p| (AudioSource::Mic, p.index, p.time_secs)),
+ );
+ let (mut tx, rx) = futures::channel::mpsc::channel::<AudioFrame>(32);
+ let duration = spec.duration;
+ audio_emits.push(tokio::spawn(async move {
+ use futures::SinkExt;
+ let first = (delay / AUDIO_CHUNK_SECS).ceil() as usize;
+ let last = (duration / AUDIO_CHUNK_SECS) as usize;
+ for k in first..last {
+ let t = k as f64 * AUDIO_CHUNK_SECS;
+ let at = base + Duration::from_secs_f64(t);
+ tokio::time::sleep_until(at.into()).await;
+ let frame =
+ AudioFrame::new(audio_chunk(&track, t, &mono_info), Timestamp::Instant(at));
+ if tx.send(frame).await.is_err() {
+ break;
+ }
+ }
+ tx
+ }));
+ builder = builder
+ .with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(mono_info, rx));
+ }
+ let audio_pipeline = if has_audio {
+ Some(
+ builder
+ .build::<DashSegmentedAudioMuxer>(DashSegmentedAudioMuxerConfig::default())
+ .await
+ .map_err(|e| anyhow!("instant audio pipeline: {e}"))?,
+ )
+ } else {
+ None
+ };
+
+ if let (Some(gate), Some(arm_at)) = (&gate, spec.arm_at) {
+ tokio::time::sleep_until((base + Duration::from_secs_f64(arm_at)).into()).await;
+ gate.arm();
+ }
+ video_emit.await.context("video emit")?;
+ let mut held = Vec::new();
+ for emit in audio_emits {
+ held.push(emit.await.context("audio emit")?);
+ }
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ video_pipeline
+ .stop()
+ .await
+ .map_err(|e| anyhow!("instant video stop: {e}"))?;
+ if let Some(audio) = audio_pipeline {
+ audio
+ .stop()
+ .await
+ .map_err(|e| anyhow!("instant audio stop: {e}"))?;
+ }
+ drop(held);
+ let output = content.join("output.mp4");
+ let display_dir = content.join("display");
+ let audio_dir = content.join("audio");
+ if !audio_dir.exists() {
+ std::fs::create_dir_all(&audio_dir)?;
+ }
+ tokio::task::spawn_blocking(move || {
+ cap_recording::recovery::RecoveryManager::finalize_instant_output(
+ &display_dir,
+ &audio_dir,
+ &output,
+ )
+ })
+ .await?
+ .map_err(|e| anyhow!("finalize instant output: {e}"))?;
+ let meta = cap_project::RecordingMeta {
+ platform: Some(cap_project::Platform::default()),
+ project_path: dir.to_path_buf(),
+ pretty_name: spec.name.clone(),
+ sharing: None,
+ inner: cap_project::RecordingMetaInner::Instant(
+ cap_project::InstantRecordingMeta::Complete {
+ fps: spec.screen.fps,
+ sample_rate: has_audio.then_some(AUDIO_RATE),
+ },
+ ),
+ upload: None,
+ };
+ meta.save_for_project()
+ .map_err(|e| anyhow!("save instant meta: {e:?}"))?;
+ if let Some(arm_at) = spec.arm_at {
+ // Frames and markers within a frame of the arm instant may land on
+ // either side of it.
+ let margin = 0.05;
+ emitted.screen.retain(|e| e.1 >= arm_at + margin);
+ emitted.audio.retain(|e| e.2 >= arm_at + margin);
+ }
+ std::fs::write(
+ dir.join("verify-emitted.json"),
+ serde_json::to_string(&emitted)?,
+ )?;
+ Ok(())
+}
diff --git a/crates/verify/tests/export.rs b/crates/verify/tests/export.rs
index ec07342ad..71b3a9828 100644
--- a/crates/verify/tests/export.rs
+++ b/crates/verify/tests/export.rs
@@ -348,3 +348,196 @@ fn recorded_studio() {
);
common::assert_passed(failures);
}
+
+/// Instant mode: the finalised `output.mp4` is the deliverable. Every
+/// emitted screen frame must appear once, in order, on its own timing, and
+/// every audio marker must be present, within 5 ms of the screen.
+#[test]
+fn instant_output() {
+ let mut failures = Vec::new();
+ for spec in catalog::instant_variants(report::tier()) {
+ if let Some(failure) = instant_case(spec) {
+ failures.push(failure);
+ }
+ }
+ common::assert_passed(failures);
+}
+
+fn instant_case(spec: cap_verify::pipeline::InstantSpec) -> Option<String> {
+ use cap_verify::{
+ audio_code::{self, AudioSource},
+ fixture, media,
+ pipeline::{self, Emitted},
+ video_code::{self, StreamKind},
+ };
+ let id = format!("export/{}/output/mp4/native", spec.name);
+ if !report::selected(&id) {
+ return None;
+ }
+ common::init();
+ let dir = fixture::ensure_fixture_keyed(spec.cache_key(), |dir| {
+ common::runtime().block_on(pipeline::record_instant(&spec, dir))
+ })
+ .expect("instant fixture");
+ let emitted: Emitted = serde_json::from_str(
+ &std::fs::read_to_string(dir.join("verify-emitted.json")).expect("emitted"),
+ )
+ .expect("emitted json");
+ let output = dir.join("content/output.mp4");
+ let mut case = Case::new(&id);
+ let mut frames = Vec::new();
+ media::decode_video(&output, |p| {
+ frames.push((
+ p.pts_secs,
+ video_code::read_stream(&p.view(), StreamKind::Screen),
+ ))
+ })
+ .expect("decode instant output");
+ let shown: Vec<(f64, u32)> = frames
+ .iter()
+ .filter_map(|(pts, r)| r.marker().map(|m| (*pts, m.index)))
+ .collect();
+ if shown.len() != frames.len() {
+ case.problem(
+ "unreadable",
+ format!(
+ "{} of {} frames unreadable",
+ frames.len() - shown.len(),
+ frames.len()
+ ),
+ );
+ }
+ let emitted_slots: Vec<u32> = emitted.screen.iter().map(|e| e.0).collect();
+ let shown_slots: Vec<u32> = shown.iter().map(|s| s.1).collect();
+ let missing: Vec<u32> = emitted_slots
+ .iter()
+ .filter(|s| !shown_slots.contains(s))
+ .copied()
+ .collect();
+ let repeated: Vec<u32> = shown_slots
+ .windows(2)
+ .filter(|w| w[1] <= w[0])
+ .map(|w| w[1])
+ .collect();
+ if !missing.is_empty() {
+ case.problem(
+ "dropped",
+ format!(
+ "{} emitted frames missing from the output (first {:?})",
+ missing.len(),
+ &missing[..missing.len().min(8)]
+ ),
+ );
+ }
+ if !repeated.is_empty() {
+ case.problem(
+ "stale",
+ format!(
+ "{} frames repeated or out of order (first {:?})",
+ repeated.len(),
+ &repeated[..repeated.len().min(8)]
+ ),
+ );
+ }
+ let emit_time = |slot: u32| {
+ emitted
+ .screen
+ .iter()
+ .find(|e| e.0 == slot)
+ .map(|e| e.1)
+ .unwrap_or(f64::NAN)
+ };
+ let video_offsets: Vec<f64> = shown.iter().map(|&(pts, s)| pts - emit_time(s)).collect();
+ let spread = |v: &[f64]| {
+ let lo = v.iter().copied().fold(f64::INFINITY, f64::min);
+ let hi = v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
+ hi - lo
+ };
+ let median = |v: &[f64]| {
+ let mut v = v.to_vec();
+ v.sort_by(f64::total_cmp);
+ v.get(v.len() / 2).copied().unwrap_or(f64::NAN)
+ };
+ let frame = 1.0 / f64::from(emitted.fps);
+ let video_spread = spread(&video_offsets);
+ case.note(format!("video timing spread {:.2} ms", video_spread * 1e3));
+ if video_spread > frame / 2.0 {
+ case.problem(
+ "timestamps",
+ format!(
+ "video frame times drift by {:.1} ms against emission (allowed {:.1})",
+ video_spread * 1e3,
+ frame / 2.0 * 1e3
+ ),
+ );
+ }
+ let audio = media::decode_audio(&output, None).expect("decode instant audio");
+ let mono = audio.mono();
+ for source in [AudioSource::Mic, AudioSource::System] {
+ let expected: Vec<(u32, f64)> = emitted
+ .audio
+ .iter()
+ .filter(|e| e.0 == source)
+ .map(|e| (e.1, e.2))
+ .collect();
+ if expected.is_empty() {
+ continue;
+ }
+ let found = audio_code::locate_markers(&mono, audio.sample_rate, source);
+ let mut offsets = Vec::new();
+ let mut absent = Vec::new();
+ for &(index, t) in &expected {
+ match found.iter().find(|f| f.index == Some(index)) {
+ Some(f) => offsets.push(f.time_secs + audio.start_secs - t),
+ None => absent.push(index),
+ }
+ }
+ let extra = found.len().saturating_sub(expected.len() - absent.len());
+ if !absent.is_empty() || extra > 0 {
+ case.problem(
+ "audio",
+ format!(
+ "{}: {} markers missing (first {:?}), {} unexpected",
+ source.name(),
+ absent.len(),
+ &absent[..absent.len().min(5)],
+ extra
+ ),
+ );
+ }
+ if offsets.is_empty() {
+ continue;
+ }
+ let av = median(&offsets) - median(&video_offsets);
+ case.note(format!(
+ "{}: {} markers, spread {:.2} ms, A/V offset {:+.2} ms",
+ source.name(),
+ offsets.len(),
+ spread(&offsets) * 1e3,
+ av * 1e3
+ ));
+ eprintln!(
+ "[cap-verify] instant {}: spread {:.2} ms, A/V {:+.2} ms",
+ source.name(),
+ spread(&offsets) * 1e3,
+ av * 1e3
+ );
+ if spread(&offsets) > 0.005 {
+ case.problem(
+ "audio",
+ format!(
+ "{} marker timing drifts by {:.2} ms",
+ source.name(),
+ spread(&offsets) * 1e3
+ ),
+ );
+ }
+ if av.abs() > 0.005 {
+ case.problem(
+ "sync",
+ format!("{} is {:+.1} ms off the screen", source.name(), av * 1e3),
+ );
+ }
+ }
+ report::settle(case).err()
+}