Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
test(verify): stimulus warm-up, start-up drop allowance, file-based child readiness
Richie McIlroydd49e9031fd7
diff --git a/crates/verify/src/bin/stimulus.rs b/crates/verify/src/bin/stimulus.rsindex cd8e89f38..4a98c689c 100644--- a/crates/verify/src/bin/stimulus.rs+++ b/crates/verify/src/bin/stimulus.rs@@ -111,6 +111,9 @@ mod app {ready: false,done: false,error: None,+ created: None,+ idle_tick: 0,+ last_idle: None,};event_loop.run_app(&mut app)?;drop(audio);@@ -150,6 +153,9 @@ mod app {ready: bool,done: bool,error: Option<String>,+ created: Option<Instant>,+ idle_tick: u32,+ last_idle: Option<Instant>,}impl App {@@ -177,7 +183,21 @@ mod app {.or(Some(now))}- fn draw(&mut self, index: u32) {+ /// Before `go` the picture keeps frame 0 but the noise bands keep+ /// moving at the frame rate, so the window server is compositing at+ /// full rate by the time the recording starts (a cold paravirtual+ /// display presents its first changes late).+ fn idle_due(&self, now: Instant) -> Option<Instant> {+ if self.go_at.is_some() {+ return None;+ }+ Some(+ self.last_idle+ .map_or(now, |t| t + Duration::from_secs_f64(1.0 / self.spec.fps)),+ )+ }++ fn draw(&mut self, index: u32, salt: u64) {let (w, h) = self.size;let Some(surface) = self.surface.as_mut() else {return;@@ -211,14 +231,22 @@ mod app {PixelOrder::Bgra,);if band > 0 {- noise_band(&mut bytes[..band * stride], w, band, index, 0);- noise_band(&mut bytes[(h - band) * stride..], w, band, index, 1);+ noise_band(&mut bytes[..band * stride], w, band, index, salt << 1);+ noise_band(+ &mut bytes[(h - band) * stride..],+ w,+ band,+ index,+ (salt << 1) | 1,+ );}}if buffer.present().is_ok() {let host = host_now();+ if self.shown != Some(index) {+ self.log.write(&StimulusEvent::Frame { index, host });+ }self.shown = Some(index);- self.log.write(&StimulusEvent::Frame { index, host });}}}@@ -316,12 +344,20 @@ mod app {}}WindowEvent::RedrawRequested => {- let index = self.desired(Instant::now());- let resized = !self.ready;- if self.shown != Some(index) || resized {- self.draw(index);+ let now = Instant::now();+ let created = *self.created.get_or_insert(now);+ let index = self.desired(now);+ if self.go_at.is_none() {+ if self.idle_due(now).is_some_and(|due| due <= now) {+ self.idle_tick += 1;+ self.last_idle = Some(now);+ self.draw(0, u64::from(self.idle_tick));+ }+ } else if self.shown != Some(index) {+ self.draw(index, 0);}- if !self.ready && self.shown == Some(0) {+ let warm = now.duration_since(created).as_secs_f64() >= self.spec.warmup;+ if !self.ready && warm && self.shown == Some(0) {self.ready = true;let scale = self.window.as_ref().map_or(1.0, |w| w.scale_factor());self.log.write(&StimulusEvent::Ready {@@ -346,11 +382,20 @@ mod app {}fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {- if self.done || self.go_at.is_none() {+ let now = Instant::now();+ if let Some(due) = self.idle_due(now) {+ if due <= now+ && let Some(window) = &self.window+ {+ window.request_redraw();+ }+ event_loop.set_control_flow(ControlFlow::WaitUntil(due.max(now)));+ return;+ }+ if self.done {event_loop.set_control_flow(ControlFlow::Wait);return;}- let now = Instant::now();if let Some(window) = &self.window&& self.desired(now) != self.shown.unwrap_or(0){diff --git a/crates/verify/src/stimulus.rs b/crates/verify/src/stimulus.rsindex f9adc4304..9cd6da9b8 100644--- a/crates/verify/src/stimulus.rs+++ b/crates/verify/src/stimulus.rs@@ -23,6 +23,8 @@ pub struct StimulusSpec {/// Pseudo-random achromatic noise bands above and below the marker, new/// every frame, so the encoder sees dense changing content.pub busy: bool,+ /// Seconds of moving noise before `ready` (frame 0 keeps showing).+ pub warmup: f64,pub audio: bool,pub audio_period: f64,/// Host time the system-audio marker schedule counts from (0 = helperdiff --git a/crates/verify/tests/recording.rs b/crates/verify/tests/recording.rsindex ff40f43cc..5c2568b68 100644--- a/crates/verify/tests/recording.rs+++ b/crates/verify/tests/recording.rs@@ -52,6 +52,10 @@ const CAMERA_SIZE: (usize, usize) = (640, 360);const AUDIO_PERIOD: f64 = 0.5;const WINDOW_TITLE: &str = "Cap Verify Stimulus";const SYSTEM_AUDIO_STARTUP: f64 = 1.0;+/// Frames a track may lose while its encoder starts (the capture pool is full+/// until VideoToolbox is ready; #2573 measured 0-6 per run).+const STARTUP_SECS: f64 = 1.0;+const STARTUP_DROPS: usize = 6;#[derive(Clone, Copy, Debug, PartialEq, Eq)]enum Mode {@@ -187,8 +191,7 @@ fn runtime() -> tokio::runtime::Runtime {.expect("runtime")}-#[test]-fn real_capture() {+fn init() {media::init();if std::env::var_os("RUST_LOG").is_some() {let _ = tracing_subscriber::fmt()@@ -196,6 +199,11 @@ fn real_capture() {.with_writer(std::io::stderr).try_init();}+}++#[test]+fn real_capture() {+ init();let Some(capture) = capture_mode() else {eprintln!("[cap-verify] recording: CAP_VERIFY_CAPTURE=off, skipping");return;@@ -477,13 +485,13 @@ fn studio_builder(struct ChildSpec {project: PathBuf,truth: PathBuf,+ ready: PathBuf,reference: u64,max_secs: f64,window: bool,}const CHILD_ENV: &str = "CAP_VERIFY_RECORD_CHILD";-const CHILD_READY: &str = "CAP-VERIFY-RECORDING";/// Child half of `studio-recovery/sigkill`: records until killed.#[test]@@ -491,7 +499,7 @@ fn recording_child() {let Ok(spec) = std::env::var(CHILD_ENV) else {return;};- media::init();+ init();let spec: ChildSpec = serde_json::from_str(&spec).expect("child spec");let rt = runtime();rt.block_on(async move {@@ -515,7 +523,7 @@ fn recording_child() {.build(Some(shareable)).await.expect("studio recording");- println!("{CHILD_READY} {} {max_fps}", host_now());+ std::fs::write(&spec.ready, format!("{} {max_fps}\n", host_now())).expect("ready");tokio::time::sleep(Duration::from_secs_f64(spec.max_secs)).await;drop(handle);});@@ -586,6 +594,10 @@ async fn record(seconds: spec.seconds,holds: spec.holds.clone(),busy: true,+ warmup: match capture {+ CaptureMode::Display => 2.0,+ CaptureMode::Window => 2.0,+ },audio: true,audio_period: AUDIO_PERIOD,audio_origin: reference,@@ -602,13 +614,6 @@ async fn record()})?;tokio::task::block_in_place(|| stimulus.wait_for("ready", Duration::from_secs(30)))?;- // A fullscreen window lands in its own Space; let the transition finish- // so the first captured frames already show the stimulus.- tokio::time::sleep(Duration::from_millis(match capture {- CaptureMode::Display => 1500,- CaptureMode::Window => 300,- }))- .await;if spec.mode == Mode::StudioKilled {return record_killed(spec, capture, scratch, reference, stimulus, case).await;}@@ -740,18 +745,18 @@ async fn record_killed(mut stimulus: StimulusProcess,case: &mut Case,) -> anyhow::Result<Recorded> {- use std::io::BufRead;-let project = scratch.join("recording.cap");let truth_path = scratch.join("mic-truth.json");let child_spec = ChildSpec {project: project.clone(),truth: truth_path.clone(),+ ready: scratch.join("child-ready.txt"),reference,max_secs: spec.seconds + 60.0,window: capture == CaptureMode::Window,};- let mut child = std::process::Command::new(std::env::current_exe()?)+ let ready_path = scratch.join("child-ready.txt");+ let child = std::process::Command::new(std::env::current_exe()?).args(["recording_child","--exact",@@ -759,35 +764,24 @@ async fn record_killed("--test-threads=1",]).env(CHILD_ENV, serde_json::to_string(&child_spec)?)- .stdout(std::process::Stdio::piped())+ .stdout(std::process::Stdio::null()).spawn()?;- let stdout = child.stdout.take();let mut child = ChildGuard(child);- let (tx, rx) = std::sync::mpsc::channel::<String>();- if let Some(stdout) = stdout {- std::thread::spawn(move || {- for line in std::io::BufReader::new(stdout)- .lines()- .map_while(Result::ok)- {- if tx.send(line).is_err() {- break;- }- }- });- }- let ready = tokio::task::block_in_place(|| {- loop {- match rx.recv_timeout(Duration::from_secs(60)) {- Ok(line) => {- if let Some(at) = line.find(CHILD_READY) {- break Ok(line[at + CHILD_READY.len()..].trim().to_string());- }- }- Err(e) => break Err(anyhow::anyhow!("recording child never started: {e}")),- }+ let deadline = std::time::Instant::now() + Duration::from_secs(60);+ let ready = loop {+ if let Ok(text) = std::fs::read_to_string(&ready_path)+ && text.ends_with('\n')+ {+ break text;}- })?;+ if std::time::Instant::now() > deadline {+ anyhow::bail!("recording child never started");+ }+ if let Ok(Some(status)) = child.0.try_wait() {+ anyhow::bail!("recording child exited early: {status}");+ }+ tokio::time::sleep(Duration::from_millis(20)).await;+ };let mut fields = ready.split_whitespace();let started_host: u64 = fields.next().unwrap_or_default().parse()?;let max_fps: u32 = fields.next().unwrap_or_default().parse()?;@@ -1152,17 +1146,30 @@ fn check_video(case: &mut Case, track: &Track, check: VideoCheck) -> anyhow::Resreturn Ok(Offsets::default());};let mut skipped = Vec::new();+ let mut startup = Vec::new();let mut explained = 0;- for &index in check.truth.keys().filter(|&&i| i > lo && i < hi) {+ let startup_end = check.truth.get(&lo).copied().unwrap_or(f64::MIN) + STARTUP_SECS;+ for (&index, &truth) in check.truth.range(lo + 1..hi) {if first_seen.contains_key(&index) || check.not_sent.contains(&index) {continue;}if (check.may_skip)(index) {explained += 1;+ } else if truth < startup_end {+ startup.push(index);} else {skipped.push(index);}}+ if startup.len() > STARTUP_DROPS {+ skipped.extend(startup.iter().copied());+ } else if !startup.is_empty() {+ case.note(format!(+ "{name}: {} start-up drops {:?} (allowed {STARTUP_DROPS} in the first {STARTUP_SECS}s)",+ startup.len(),+ startup+ ));+ }if !skipped.is_empty() {case.problem("missing",