Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
test(verify): port the round-3 gap-closing oracles
Richie McIlroy50c5fa8ecb94
diff --git a/apps/desktop-gpui/src/upload/verify_tests.rs b/apps/desktop-gpui/src/upload/verify_tests.rsindex 425cda65f..d03443041 100644--- a/apps/desktop-gpui/src/upload/verify_tests.rs+++ b/apps/desktop-gpui/src/upload/verify_tests.rs@@ -1301,6 +1301,14 @@ async fn share(project: &Path, cancel: Arc<AtomicBool>) -> StudioRun {&& progress.iter().all(|value| (0.0..=1.0).contains(value)),"progress is not monotonic within 0..=1: {progress:?}");+ // 100% means shared: only the final report after completion may be 1.0.+ assert!(+ progress+ .split_last()+ .is_none_or(|(_, earlier)| earlier.iter().all(|value| *value < 1.0))+ && (result.is_ok() || progress.iter().all(|value| *value < 1.0)),+ "progress reached 100% before the upload completed: {progress:?}"+ );StudioRun { result, progress }}diff --git a/crates/verify/expectations.toml b/crates/verify/expectations.tomlindex 7a7bcc189..5245a213c 100644--- a/crates/verify/expectations.toml+++ b/crates/verify/expectations.toml@@ -283,3 +283,10 @@ case = "export/basic/colour-red/mp430/*"class = "colour-matrix"reason = "NEW: same root cause as colour-level (BT.601 coefficients in an export tagged BT.709): background (220,40,40) decodes Cb about 9 code values low"link = ""++[[xfail]]+case = "playback/basic/cuts-speeds-reorder/realtime30-from25/avf"+class = "stale"+platforms = ["macos"]+reason = "NEW: the real-time playback loop (cap_editor::Playback prefetch, AVAssetReader) shows source frame 58 instead of 59 for the last two output frames of the 0.5x segment that follows the 2x segment (4.200 s and 4.233 s, screen and camera); offline frame stepping and export of the same timeline show 59. Deterministic, 3 of 3 runs on Apple silicon"+link = ""diff --git a/crates/verify/src/audio_model.rs b/crates/verify/src/audio_model.rsindex 264835b21..87947b633 100644--- a/crates/verify/src/audio_model.rs+++ b/crates/verify/src/audio_model.rs@@ -7,12 +7,21 @@//! - Timeline segments play back to back; segment `k` covers//! `(end - start) / timescale` output seconds and maps output time `u` in it//! to recording time `start + u * timescale`. A transition into segment `k`-//! overlaps the two segments by its clamped duration; markers inside the-//! overlap may be heard at any level (a blend) and are not required.+//! overlaps the two segments by its clamped duration. A cross-fade mixes+//! the outgoing clip at `cos(p * pi / 2)` and the incoming one at+//! `sin(p * pi / 2)` (equal power, `p` = progress through the overlap); a+//! fade through black at `max(1 - 2p, 0)` and `max(2p - 1, 0)`. Markers+//! wholly inside the overlap whose blend gain is at least+//! `BLEND_REQUIRED_GAIN` must be heard at that gain; the rest may be heard+//! at any level.//! - A recording audio track sample at track time `t` plays at recording time//! `t - offset`, where `offset` is the clip's stored offset for that track//! (mic or system audio; auto-calculated offsets align every track to the//! latest track start).+//! - Stale-startup repair: a track whose recording-meta gap summary reports+//! at least 3 startup overlap drops, at least 3 dropped frames and 100 to+//! 2000 ms of startup overlap trimmed plays that many ms earlier (its offset+//! is reduced by the trimmed time).//! - Track gain is `10^(dB / 20)`; at or below -30 dB, or with the project//! muted, the track is silent. Clip volume multiplies the recording mix. A//! mono track is centre-panned at -3 dB (0.707 per channel).@@ -29,7 +38,10 @@use std::path::Path;use anyhow::{Context, bail};-use cap_project::{ClipSpeedAudioMode, ProjectConfiguration, RecordingMeta, StudioRecordingMeta};+use cap_project::{+ ClipSpeedAudioMode, ClipTransitionType, ProjectConfiguration, RecordingMeta,+ StudioRecordingMeta,+};use serde::{Deserialize, Serialize};use crate::{@@ -56,6 +68,23 @@ const MIN_HEARD_GAIN: f64 = 1e-3;const CROSSTALK_CORRELATION: f64 = 0.8;const MIN_TRANSITION: f64 = 0.05;const MONO_PAN: f64 = 0.707;+/// Blend gain from which a marker inside a transition must be heard (and its+/// level checked); quieter blended markers may be missed by the detector.+const BLEND_REQUIRED_GAIN: f64 = 0.75;+/// Offset of the point a marker's level is measured at (the chirp centre).+const CHIRP_CENTRE_SECS: f64 = 0.010;++/// Gain a transition applies to the outgoing (`incoming == false`) or+/// incoming clip at progress `p`.+fn blend_gain(kind: ClipTransitionType, p: f64, incoming: bool) -> f64 {+ let p = p.clamp(0.0, 1.0);+ match (kind, incoming) {+ (ClipTransitionType::CrossFade, false) => (p * std::f64::consts::FRAC_PI_2).cos(),+ (ClipTransitionType::CrossFade, true) => (p * std::f64::consts::FRAC_PI_2).sin(),+ (ClipTransitionType::FadeThroughBlack, false) => (1.0 - 2.0 * p).max(0.0),+ (ClipTransitionType::FadeThroughBlack, true) => (2.0 * p - 1.0).max(0.0),+ }+}/// One marker found in a source file.#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]@@ -244,6 +273,7 @@ struct ModelSegment {mode: ClipSpeedAudioMode,volume: f64,transition_in: f64,+ transition_kind: ClipTransitionType,}impl ModelSegment {@@ -283,12 +313,25 @@ impl AudioModel {.timeline.as_ref().ok_or_else(|| anyhow::anyhow!("project has no timeline"))?;+ let repair = |audio: Option<&cap_project::AudioMeta>| {+ audio+ .and_then(|a| a.gap_summary.as_ref())+ .filter(|s| {+ s.startup_overlap_drops >= 3+ && s.overlap_dropped_frames >= 3+ && (100..=2000).contains(&s.startup_overlap_trimmed_ms)+ })+ .map_or(0.0, |s| -f64::from(s.startup_overlap_trimmed_ms) / 1000.0)+ };let offsets: Vec<ClipAudioOffsets> = (0..inner.segments.len()).map(|i| {let clip = project.clips.iter().find(|c| c.index as usize == i);+ let segment = &inner.segments[i];ClipAudioOffsets {- mic: clip.map_or(0.0, |c| f64::from(c.offsets.mic)),- system: clip.map_or(0.0, |c| f64::from(c.offsets.system_audio)),+ mic: clip.map_or(0.0, |c| f64::from(c.offsets.mic))+ + repair(segment.mic.as_ref()),+ system: clip.map_or(0.0, |c| f64::from(c.offsets.system_audio))+ + repair(segment.system_audio.as_ref()),}}).collect();@@ -307,6 +350,7 @@ impl AudioModel {.unwrap_or(1.0).clamp(0.0, 2.0),transition_in: 0.0,+ transition_kind: ClipTransitionType::CrossFade,}).collect();for transition in &timeline.transitions {@@ -318,6 +362,7 @@ impl AudioModel {if transition.duration.is_finite() && transition.duration > 0.0 && max >= MIN_TRANSITION{segments[k].transition_in = transition.duration.clamp(MIN_TRANSITION, max);+ segments[k].transition_kind = transition.kind;}}let mut output_starts = Vec::with_capacity(segments.len());@@ -332,13 +377,19 @@ impl AudioModel {let mut expected = Vec::new();let mut unchecked = Vec::new();let mut rate_windows = Vec::new();+ // Whether each recording marker in `expected` sounds inside a transition.+ let mut in_blend: Vec<bool> = Vec::new();for (k, segment) in segments.iter().enumerate() {let out_start = output_starts[k];let out_end = out_start + segment.duration();// Output window shared with a neighbour's transition.let blend_until = out_start + segment.transition_in;- let blend_from = out_end - segments.get(k + 1).map_or(0.0, |n| n.transition_in);+ let next_in = segments.get(k + 1).map_or(0.0, |n| n.transition_in);+ let next_kind = segments+ .get(k + 1)+ .map_or(ClipTransitionType::CrossFade, |n| n.transition_kind);+ let blend_from = out_end - next_in;let Some(clip_truth) = truth.segments.get(segment.clip) else {continue;};@@ -392,10 +443,23 @@ impl AudioModel {let time = out_start + (recording_time - segment.start) / segment.timescale;let whole = recording_time >= segment.start&& recording_time + marker_len <= segment.end;- let blended =- time < blend_until || time + MARKER_SECS / segment.timescale > blend_from;+ let marker_end = time + MARKER_SECS / segment.timescale;+ let blended = time < blend_until || marker_end > blend_from;+ // Blend gain when the whole marker lies in one overlap.+ let blend = if !blended {+ Some(1.0)+ } else if marker_end <= blend_until && time >= out_start {+ let p = (time + CHIRP_CENTRE_SECS - out_start) / segment.transition_in;+ Some(blend_gain(segment.transition_kind, p, true))+ } else if time >= blend_from && marker_end <= out_end && next_in > 0.0 {+ let p = (time + CHIRP_CENTRE_SECS - blend_from) / next_in;+ Some(blend_gain(next_kind, p, false))+ } else {+ None+ };let level_known = !processed && segment.volume > 0.0;- let presence = if whole && !blended && segment.volume > 0.0 {+ let audible = blend.filter(|&b| !blended || b >= BLEND_REQUIRED_GAIN);+ let presence = if whole && audible.is_some() && segment.volume > 0.0 {Presence::Required} else {Presence::Optional@@ -403,12 +467,14 @@ impl AudioModel {if segment.volume == 0.0 {continue;}+ in_blend.push(blended);expected.push(ExpectedMarker {source: track.source,index: marker.index,time_secs: time,- gain: (level_known && !blended)- .then_some(marker.gain * pan * gain * segment.volume),+ gain: audible+ .filter(|_| level_known)+ .map(|b| marker.gain * pan * gain * segment.volume * b),presence,rate: if retimed { segment.timescale } else { 1.0 },recording: Some((segment.clip, recording_time)),@@ -418,6 +484,27 @@ impl AudioModel {}}+ // Two markers of one source sounding at once (the two sides of a+ // transition) disturb each other's detection: neither is required.+ let overlapping: Vec<bool> = expected+ .iter()+ .zip(&in_blend)+ .map(|(e, &blended)| {+ blended+ && expected.iter().any(|o: &ExpectedMarker| {+ !std::ptr::eq(e, o)+ && o.source == e.source+ && (o.time_secs - e.time_secs).abs() < MARKER_SECS + 0.005+ })+ })+ .collect();+ for (e, overlaps) in expected.iter_mut().zip(overlapping) {+ if overlaps {+ e.presence = Presence::Optional;+ e.gain = None;+ }+ }+for music in &timeline.audio_segments {let gain = if music.volume_db <= -60.0 {continue;diff --git a/crates/verify/src/model.rs b/crates/verify/src/model.rsindex 602552e07..dd8da79dd 100644--- a/crates/verify/src/model.rs+++ b/crates/verify/src/model.rs@@ -112,6 +112,7 @@ enum Mapping {outgoing: (usize, f64),incoming: (usize, f64),crossfade: bool,+ progress: f64,},}@@ -276,6 +277,7 @@ impl ReferenceModel {outgoing: (k - 1, prev.start + out_tick * prev.timescale),incoming: (k, segment.start + elapsed * segment.timescale),crossfade: segment.crossfade,+ progress: (elapsed / segment.transition_in).clamp(0.0, 1.0),});}if t >= start + segment.transition_in && t < start + segment.duration() - next_in {@@ -405,6 +407,7 @@ impl ReferenceModel {outgoing,incoming,crossfade,+ progress,}) => {if !crossfade {return unchecked("fade-through-black transition");@@ -429,6 +432,7 @@ impl ReferenceModel {) => StreamExpectation::Blend {outgoing: (sa, aa),incoming: (sb, ab),+ progress,},(StreamExpectation::Absent, StreamExpectation::Absent) => {StreamExpectation::Absentdiff --git a/crates/verify/src/oracle.rs b/crates/verify/src/oracle.rsindex ef0216864..26129b195 100644--- a/crates/verify/src/oracle.rs+++ b/crates/verify/src/oracle.rs@@ -21,6 +21,11 @@ pub enum StreamExpectation {Blend {outgoing: (u8, Vec<u32>),incoming: (u8, Vec<u32>),+ /// Transition progress (0 = all outgoing). The measured blend weight+ /// must be within `BLEND_PROGRESS_TOLERANCE` of it (the tolerance+ /// covers blending in linear light, where the code's luma weight is+ /// a gamma curve of the progress).+ progress: f64,},/// Not checked, with the reason.Unchecked { reason: String },@@ -62,8 +67,14 @@ pub enum MismatchKind {Missing,/// The stream should be hidden and is visible.Unexpected,+ /// A transition frame blends the right two frames with the wrong weight.+ BlendWeight,}+/// Largest allowed difference between a transition frame's measured blend+/// weight and the transition progress.+pub const BLEND_PROGRESS_TOLERANCE: f64 = 0.35;+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]pub struct Mismatch {/// Position in the checked sequence (request number for seek runs).@@ -90,6 +101,8 @@ pub struct StreamReport {pub unreadable: u32,pub missing: u32,pub unexpected: u32,+ #[serde(default)]+ pub blend_weight: u32,pub max_ahead: i64,pub max_stale: i64,/// Source frames the model shows that never appeared.@@ -107,6 +120,7 @@ impl StreamReport {+ self.unreadable+ self.missing+ self.unexpected+ + self.blend_weight}pub fn passed(&self) -> bool {@@ -126,6 +140,7 @@ impl StreamReport {("unreadable", self.unreadable),("missing", self.missing),("unexpected", self.unexpected),+ ("blended with the wrong weight", self.blend_weight),] {if n > 0 {parts.push(format!("{n} {label}"));@@ -148,15 +163,19 @@ impl StreamReport {.mismatches.iter().take(4)- .map(|m| {- format!(+ .map(|m| match (&m.kind, &m.detail) {+ (MismatchKind::BlendWeight, Some(detail)) => format!(+ "#{} frame {} ({:.3}s) {detail}",+ m.position, m.output_frame, m.time_secs+ ),+ _ => format!("#{} frame {} ({:.3}s) expected {} got {}",m.position,m.output_frame,m.time_secs,m.expected.map_or("-".into(), |(s, i)| format!("{s}:{i}")),m.observed.map_or("-".into(), |(s, i)| format!("{s}:{i}")),- )+ ),}).collect();text.push_str(&format!("; {}", shown.join("; ")));@@ -255,8 +274,31 @@ pub fn check_stream_at(}}}- StreamExpectation::Blend { outgoing, incoming } => {+ StreamExpectation::Blend {+ outgoing,+ incoming,+ progress: expected_progress,+ } => {report.checked += 1;+ if let Readout::Blend {+ progress: observed, ..+ } = readout+ && (observed - expected_progress).abs() > BLEND_PROGRESS_TOLERANCE+ {+ report.blend_weight += 1;+ report.mismatches.push(Mismatch {+ position,+ output_frame: frame,+ time_secs,+ kind: MismatchKind::BlendWeight,+ expected: None,+ observed: None,+ delta: None,+ detail: Some(format!(+ "transition blend weight {observed:.2}, expected progress {expected_progress:.2}"+ )),+ });+ }let sides: Vec<(u8, u32)> = match readout {Readout::Blend {outgoing: o,@@ -428,7 +470,10 @@ pub fn read_expecting(expectation: &StreamExpectation,) -> Readout {use crate::video_code::{self, BLEND_TOLERANCE, FrameMarker};- let StreamExpectation::Blend { outgoing, incoming } = expectation else {+ let StreamExpectation::Blend {+ outgoing, incoming, ..+ } = expectation+ else {return video_code::read_stream(img, kind);};let cells = match video_code::read_cells(img, kind) {diff --git a/crates/verify/src/pipeline.rs b/crates/verify/src/pipeline.rsindex 18d8fc484..cc9620800 100644--- a/crates/verify/src/pipeline.rs+++ b/crates/verify/src/pipeline.rs@@ -98,12 +98,92 @@ pub struct RecordedSpec {}impl RecordedSpec {- /// Key for the fixture cache.+ /// Key for the fixture cache: the spec plus the recording code that made+ /// the fixture ([`product_source_hash`]).pub fn cache_key(&self) -> String {- crate::fixture::cache_key(&self.name, self)+ crate::fixture::cache_key(&self.name, &(self, product_source_hash()))}}+/// Workspace crates whose code shapes a recorded fixture (capture pipeline,+/// muxers, encoders, timestamps, audio conversion).+const RECORDING_SOURCE_CRATES: &[&str] = &[+ "recording",+ "cap-muxer",+ "cap-muxer-protocol",+ "enc-ffmpeg",+ "enc-avfoundation",+ "enc-mediafoundation",+ "media-info",+ "media",+ "timestamp",+ "audio",+ "frame-converter",+ "project",+];++/// Hash of the product sources that recorded fixtures are made by. Recorded+/// fixtures are product output: keying them by the spec alone would let a+/// cached fixture recorded by older code (the CI fixture cache is keyed by+/// the generator sources only) hide a regression in the recording pipeline.+/// With this in the key, any change to those crates, to Cargo.lock or to+/// this recorder harness re-records the fixtures.+pub fn product_source_hash() -> u64 {+ static HASH: std::sync::OnceLock<u64> = std::sync::OnceLock::new();+ *HASH.get_or_init(|| {+ fn collect(dir: &Path, out: &mut Vec<std::path::PathBuf>) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ if path.file_name().is_some_and(|n| n != "target") {+ collect(&path, out);+ }+ } else if path+ .extension()+ .is_some_and(|e| e == "rs" || e == "toml" || e == "wgsl" || e == "metal")+ {+ out.push(path);+ }+ }+ }+ let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));+ let root = manifest+ .join("../..")+ .canonicalize()+ .unwrap_or_else(|_| manifest.join("../.."));+ let mut files = Vec::new();+ for name in RECORDING_SOURCE_CRATES {+ collect(&root.join("crates").join(name), &mut files);+ }+ files.push(root.join("Cargo.lock"));+ files.push(root.join("crates/verify/src/pipeline.rs"));+ files.sort();+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ let mut feed = |bytes: &[u8]| {+ for &byte in bytes {+ hash ^= u64::from(byte);+ hash = hash.wrapping_mul(0x0100_0000_01b3);+ }+ };+ for file in &files {+ let Ok(contents) = std::fs::read(file) else {+ continue;+ };+ feed(+ file.strip_prefix(&root)+ .unwrap_or(file)+ .to_string_lossy()+ .as_bytes(),+ );+ feed(&contents);+ }+ hash+ })+}+fn bgra_frame(marker: FrameMarker, width: u32, height: u32) -> ffmpeg::frame::Video {let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, width, height);let stride = frame.stride(0);@@ -152,6 +232,23 @@ fn audio_chunk(track: &[f32], chunk_t: f64, info: &AudioInfo) -> ffmpeg::frame::frame}+/// Emitters wait for this before their first frame, so every device starts+/// delivering only once all pipelines are built. Emitting from the pipeline+/// epoch instead queued the frames of a slow setup and delivered them as a+/// burst, which the recorder (rightly) treats as stale overlap and drops.+type StartGate = tokio::sync::watch::Receiver<Option<std::time::Instant>>;++async fn started(mut gate: StartGate) -> std::time::Instant {+ loop {+ if let Some(base) = *gate.borrow() {+ return base;+ }+ if gate.changed().await.is_err() {+ return std::time::Instant::now();+ }+ }+}+struct VideoLeg {pipeline: OutputPipeline,emit: tokio::task::JoinHandle<()>,@@ -167,15 +264,16 @@ async fn video_leg(video: &RecordedVideo,duration: f64,timestamps: Timestamps,+ start: StartGate,) -> anyhow::Result<VideoLeg> {let info = VideoInfo::from_raw(RawVideoFormat::Bgra, video.width, video.height, video.fps);let (tx, rx) = flume::bounded::<FFmpegVideoFrame>(32);- let base = timestamps.instant();let slots = video.delivery.slots(video.fps, duration - video.start_delay);let (fps, width, height, delay) = (video.fps, video.width, video.height, video.start_delay);let emit = tokio::spawn(async move {+ let base = started(start).await;for slot in slots {let t = delay + f64::from(slot) / f64::from(fps);let at = base + Duration::from_secs_f64(t);@@ -214,7 +312,7 @@ async fn record_segment(std::fs::create_dir_all(dir.join(&seg))?;let rel = |file: &str| RelativePathBuf::from(format!("{seg}/{file}"));let timestamps = Timestamps::now();- let base = timestamps.instant();+ let (start_tx, start) = tokio::sync::watch::channel(None);let screen = video_leg(dir,@@ -224,6 +322,7 @@ async fn record_segment(&spec.screen,spec.duration,timestamps,+ start.clone(),).await?;let camera = match &spec.camera {@@ -236,6 +335,7 @@ async fn record_segment(camera,spec.duration,timestamps,+ start.clone(),).await?,),@@ -252,8 +352,10 @@ async fn record_segment(let track = marker_track(AudioSource::Mic, spec.duration);let (mut tx, rx) = futures::channel::mpsc::channel::<AudioFrame>(32);let duration = spec.duration;+ let gate = start.clone();let emit = tokio::spawn(async move {use futures::SinkExt;+ let base = started(gate).await;let first = (delay / AUDIO_CHUNK_SECS).ceil() as usize;let last = (duration / AUDIO_CHUNK_SECS) as usize;for k in first..last {@@ -283,8 +385,10 @@ async fn record_segment(let schedule =audio_code::standard_schedule(AudioSource::System, 0.1, spec.duration - 0.1, 0.5);let (mut tx, rx) = futures::channel::mpsc::channel::<AudioFrame>(32);+ let gate = start.clone();let emit = tokio::spawn(async move {use futures::SinkExt;+ let base = started(gate).await;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)@@ -314,6 +418,8 @@ async fn record_segment(system = Some((pipeline, emit, rel("system_audio.ogg")));}+ let _ = start_tx.send(Some(std::time::Instant::now() + Duration::from_millis(50)));+// Wait for every device to finish delivering, keeping the audio senders// open (real devices deliver until stop), then stop like the recorder.screen.emit.await.context("screen emit")?;@@ -462,8 +568,12 @@ pub struct InstantSpec {}impl InstantSpec {+ /// Key for the fixture cache, including [`product_source_hash`].pub fn cache_key(&self) -> String {- crate::fixture::cache_key(&format!("instant-{}", self.name), self)+ crate::fixture::cache_key(+ &format!("instant-{}", self.name),+ &(self, product_source_hash()),+ )}}diff --git a/crates/verify/src/report.rs b/crates/verify/src/report.rsindex 9ac742457..5987c9950 100644--- a/crates/verify/src/report.rs+++ b/crates/verify/src/report.rs@@ -141,6 +141,7 @@ impl Case {("unreadable", report.unreadable),("missing", report.missing),("unexpected", report.unexpected),+ ("blend", report.blend_weight),] {if n > 0 {self.classes.insert(class.to_string());diff --git a/crates/verify/tests/audio.rs b/crates/verify/tests/audio.rsindex 47304fd40..3b7c12355 100644--- a/crates/verify/tests/audio.rs+++ b/crates/verify/tests/audio.rs@@ -93,6 +93,21 @@ fn transition(config: &mut ProjectConfiguration) {common::add_transition(config, 1, 0.4);}+/// A long cross-fade: markers early in the overlap must keep the outgoing+/// clip's level and the incoming clip must ramp up (equal-power gains).+fn long_crossfade(config: &mut ProjectConfiguration) {+ common::set_cuts(config, &[(0.3, 4.1, 1.0), (3.9, 7.8, 1.0)]);+ common::add_transition(config, 1, 1.8);+}++/// A long fade through black: each side fades linearly to silence over half+/// the overlap.+fn long_fade_black(config: &mut ProjectConfiguration) {+ long_crossfade(config);+ config.timeline.as_mut().expect("timeline").transitions[0].kind =+ cap_project::ClipTransitionType::FadeThroughBlack;+}+fn variants() -> Vec<Variant> {vec![Variant {@@ -131,6 +146,14 @@ fn variants() -> Vec<Variant> {edit: "transition",apply: transition,},+ Variant {+ edit: "long-crossfade",+ apply: long_crossfade,+ },+ Variant {+ edit: "long-fade-black",+ apply: long_fade_black,+ },]}@@ -188,6 +211,19 @@ fn export_case_at(common::read_output(&out, Some(&|i| video.expect(i as u32, fps)));common::check_sequence(&mut case, &video, &frames, fps, true);audio_support::check_av(&mut case, &project.meta, &report, &frames, fps);+ // The audio track must cover the whole video, and end+ // within one AAC frame (encoder padding) after it.+ let audio_secs = mono.len() as f64 / f64::from(audio_model::ANALYSIS_RATE);+ let video_secs = frames.len() as f64 / f64::from(fps);+ let slack = 1024.0 / f64::from(audio_model::ANALYSIS_RATE) + 0.001;+ if audio_secs < video_secs - 0.002 || audio_secs > video_secs + slack {+ case.problem(+ "audio-duration",+ format!(+ "audio track lasts {audio_secs:.4} s, video {video_secs:.4} s (slack {slack:.4} s)"+ ),+ );+ }}}}@@ -682,3 +718,166 @@ fn oracle_self_check() {}common::finish(case);}++/// Stereo system audio recorded on the left channel only must come out on+/// the left channel only. Every other case mixes identical channels and+/// checks the channel average, so it cannot see swapped or summed channels.+#[test]+fn stereo_channels() {+ use cap_verify::{+ audio_code::{self, AudioSource},+ fixture,+ media::{self, AudioCodec},+ };+ let id = format!("audio/stereo-left/full/{}{FPS}", ExportPath::App.label());+ if !report::selected(&id) {+ return;+ }+ common::init();+ let mut spec = audio_fixture::mix(report::tier());+ spec.name = format!("{}-left", spec.name);+ spec.segments[0].mic = None;+ let path = fixture::ensure_fixture(&spec, |spec, dir| {+ audio_fixture::write(spec, dir)?;+ let file = dir.join("content/segments/segment-0/system_audio.ogg");+ let decoded = media::decode_audio(&file, None)?;+ let left = decoded.channels[0].clone();+ let right = vec![0.0; left.len()];+ media::write_audio(+ &file,+ &[left, right],+ decoded.sample_rate,+ AudioCodec::Opus,+ 96_000,+ )+ })+ .unwrap_or_else(|e| panic!("fixture {}: {e:?}", spec.name));+ let project = common::load(&spec.name, path);+ let config = project.config();+ let model = audio_support::audio_model(&project, &config);+ let required = model+ .expected+ .iter()+ .filter(|e| {+ e.source == AudioSource::System && e.presence == audio_model::Presence::Required+ })+ .count();+ let mut case = Case::new(&id);+ let dir = common::scratch_dir(&id);+ match common::runtime().block_on(audio_support::export(+ &project,+ config,+ ExportPath::App,+ FPS,+ RES,+ dir.path(),+ )) {+ Err(e) => case.problem("error", format!("export failed: {e}")),+ Ok(out) => match media::decode_audio(&out, Some(audio_model::ANALYSIS_RATE)) {+ Err(e) => case.problem("error", format!("decode audio: {e:?}")),+ Ok(decoded) if decoded.channels.len() != 2 => case.problem(+ "audio-channels",+ format!(+ "export has {} audio channels, expected 2",+ decoded.channels.len()+ ),+ ),+ Ok(decoded) => {+ let heard = |channel: &[f32]| {+ audio_code::locate_markers(+ channel,+ audio_model::ANALYSIS_RATE,+ AudioSource::System,+ )+ .into_iter()+ .filter(|m| m.index.is_some() && m.gain > 0.02)+ .count()+ };+ let (left, right) = (heard(&decoded.channels[0]), heard(&decoded.channels[1]));+ if left < required || right > 0 {+ case.problem(+ "audio-channels",+ format!(+ "left-only system audio: {left} markers heard on the left (expected {required}), {right} on the right (expected 0)"+ ),+ );+ }+ }+ },+ }+ common::finish(case);+}++/// A recording whose mic gap summary reports a stale startup burst: the+/// editor plays the mic earlier by the trimmed time (stale-startup repair),+/// in exports and in playback.+#[test]+fn timing_repair() {+ use cap_verify::fixture;+ common::init();+ let mut spec = audio_fixture::mix(report::tier());+ spec.name = format!("{}-repair", spec.name);+ let path = fixture::ensure_fixture(&spec, |spec, dir| {+ audio_fixture::write(spec, dir)?;+ let meta_path = dir.join("recording-meta.json");+ let mut meta: serde_json::Value = serde_json::from_slice(&std::fs::read(&meta_path)?)?;+ meta["segments"][0]["mic"]["gap_summary"] = serde_json::json!({+ "total_overlap_trimmed_ms": 300,+ "startup_overlap_trimmed_ms": 300,+ "overlap_dropped_frames": 4,+ "startup_overlap_drops": 4+ });+ std::fs::write(&meta_path, serde_json::to_vec_pretty(&meta)?)?;+ Ok(())+ })+ .unwrap_or_else(|e| panic!("fixture {}: {e:?}", spec.name));+ let project = common::load(&spec.name, path);+ let config = project.config();+ let model = audio_support::audio_model(&project, &config);+ let mut failures = Vec::new();+ for path in [ExportPath::App, ExportPath::Plain] {+ let id = format!("audio/{}/full/{}{FPS}", spec.name, path.label());+ if !report::selected(&id) {+ continue;+ }+ let mut case = Case::new(&id);+ let dir = common::scratch_dir(&id);+ match common::runtime().block_on(audio_support::export(+ &project,+ config.clone(),+ path,+ FPS,+ RES,+ dir.path(),+ )) {+ Err(e) => case.problem("error", format!("export failed: {e}")),+ Ok(out) => match audio_support::exported_mono(&out) {+ Err(e) => case.problem("error", e),+ Ok(mono) => {+ audio_support::check_pcm(&mut case, "export", &model, &mono);+ }+ },+ }+ if let Err(message) = report::settle(case) {+ failures.push(message);+ }+ }+ let id = format!("audio/{}/full/playback", spec.name);+ if report::selected(&id) {+ let rt = common::runtime();+ let mut case = Case::new(&id);+ let mut player = OfflinePlayer::open(&rt, &project, config);+ player.play(0.0);+ let pcm = player.pull(model.duration + 0.3);+ audio_support::check_pcm(+ &mut case,+ "play from 0",+ &model.window(0.0, audio_support::frames_secs(&pcm)),+ &audio_support::mono(&pcm),+ );+ if let Err(message) = report::settle(case) {+ failures.push(message);+ }+ }+ common::assert_passed(failures);+}diff --git a/crates/verify/tests/common/mod.rs b/crates/verify/tests/common/mod.rsindex fa051b2e9..d534a2f47 100644--- a/crates/verify/tests/common/mod.rs+++ b/crates/verify/tests/common/mod.rs@@ -53,7 +53,7 @@ pub fn project(spec: &FixtureSpec) -> Project {load(&spec.name, path)}-fn load(name: &str, path: PathBuf) -> Project {+pub fn load(name: &str, path: PathBuf) -> Project {let meta = RecordingMeta::load_for_project(&path).expect("fixture meta");let truth = SourceTruth::read(&path).expect("fixture truth");Project {@@ -325,8 +325,128 @@ pub struct OutputFrame {pub readout: FrameReadout,/// Hash of the decoded picture, for determinism checks.pub hash: u64,+ /// Picture size.+ pub size: (usize, usize),+ /// Camera key region of every `LAYOUT_SAMPLE_EVERY`th frame, as fractions+ /// of the picture size.+ pub camera_region: Option<video_code::Region>,+ /// Mean Y, Cb, Cr code values of a flat band of the screen's key colour+ /// and the stream's colour tag, sampled like `camera_region` (YUV+ /// outputs only).+ pub screen_colour: Option<ScreenColour>,}+#[derive(Clone, Copy, Debug)]+pub struct ScreenColour {+ pub ycbcr: [f64; 3],+ pub space: ffmpeg::util::color::Space,+ pub range: ffmpeg::util::color::Range,+}++/// Measured minus expected (Y, Cb, Cr) code values for `rgb` encoded the way+/// the stream's colour tag says (BT.709 unless tagged BT.601; limited range+/// unless tagged full).+pub fn colour_error(colour: &ScreenColour, rgb: [u8; 3]) -> [f64; 3] {+ use ffmpeg::util::color::{Range, Space};+ let [r, g, b] = rgb.map(|v| f64::from(v) / 255.0);+ let (kr, kb) = if matches!(colour.space, Space::BT470BG | Space::SMPTE170M) {+ (0.299, 0.114)+ } else {+ (0.2126, 0.0722)+ };+ let y = kr * r + (1.0 - kr - kb) * g + kb * b;+ let (cb, cr) = ((b - y) / (2.0 * (1.0 - kb)), (r - y) / (2.0 * (1.0 - kr)));+ let expected = if colour.range == Range::JPEG {+ [255.0 * y, 128.0 + 255.0 * cb, 128.0 + 255.0 * cr]+ } else {+ [16.0 + 219.0 * y, 128.0 + 224.0 * cb, 128.0 + 224.0 * cr]+ };+ [0, 1, 2].map(|k| colour.ycbcr[k] - expected[k])+}++/// Mean code values and tag of a rectangle (fractions of the picture).+pub fn rect_colour(+ frame: &ffmpeg::frame::Video,+ view: &impl video_code::PixelSource,+ rect: [f64; 4],+) -> Option<ScreenColour> {+ if !matches!(+ frame.format(),+ ffmpeg::format::Pixel::YUV420P | ffmpeg::format::Pixel::NV12+ ) {+ return None;+ }+ let (w, h) = (view.width() as f64, view.height() as f64);+ let (x0, x1) = (+ (rect[0] * w) as usize,+ ((rect[2] * w) as usize).max((rect[0] * w) as usize + 1),+ );+ let (y0, y1) = (+ (rect[1] * h) as usize,+ ((rect[3] * h) as usize).max((rect[1] * h) as usize + 1),+ );+ let mut sum = [0.0; 3];+ let mut n = 0.0;+ for y in y0..y1 {+ for x in x0..x1 {+ let (cb, cr) = view.chroma(x, y);+ sum[0] += view.luma(x, y);+ sum[1] += cb + 128.0;+ sum[2] += cr + 128.0;+ n += 1.0;+ }+ }+ Some(ScreenColour {+ ycbcr: sum.map(|v| v / n),+ space: frame.color_space(),+ range: frame.color_range(),+ })+}++/// Mean code values of the band 8-16% down the screen's key region, 20-80%+/// across (above the code square and the default camera position).+fn screen_colour(+ frame: &ffmpeg::frame::Video,+ view: &impl video_code::PixelSource,+) -> Option<ScreenColour> {+ if !matches!(+ frame.format(),+ ffmpeg::format::Pixel::YUV420P | ffmpeg::format::Pixel::NV12+ ) {+ return None;+ }+ let region = video_code::locate_region(view, StreamKind::Screen)?;+ let (w, h) = (region.x1 - region.x0, region.y1 - region.y0);+ let (x0, x1) = (+ (region.x0 + 0.2 * w) as usize,+ (region.x0 + 0.8 * w) as usize,+ );+ let (y0, y1) = (+ (region.y0 + 0.08 * h) as usize,+ (region.y0 + 0.16 * h) as usize,+ );+ let mut sum = [0.0; 3];+ let mut n = 0.0;+ for y in y0..y1.max(y0 + 1) {+ for x in x0..x1.max(x0 + 1) {+ let (cb, cr) = view.chroma(x, y);+ sum[0] += view.luma(x, y);+ sum[1] += cb + 128.0;+ sum[2] += cr + 128.0;+ n += 1.0;+ }+ }+ Some(ScreenColour {+ ycbcr: sum.map(|v| v / n),+ space: frame.color_space(),+ range: frame.color_range(),+ })+}++/// Frames between camera placement samples (placement does not change+/// between frames of the verification projects).+pub const LAYOUT_SAMPLE_EVERY: usize = 10;+fn picture_hash(frame: &ffmpeg::frame::Video) -> u64 {let mut hash: u64 = 0xcbf2_9ce4_8422_2325;let planes = if frame.format() == ffmpeg::format::Pixel::NV12 {@@ -366,10 +486,30 @@ pub fn read_output(Some(expect) => read_expecting(&view, &expect(frames.len())),None => video_code::read_frame(&view),};+ let size = (+ picture.frame.width() as usize,+ picture.frame.height() as usize,+ );+ let camera_region = (frames.len() % LAYOUT_SAMPLE_EVERY == 0+ && matches!(readout.camera, video_code::Readout::Marker { .. }))+ .then(|| video_code::locate_region(&view, StreamKind::Camera))+ .flatten()+ .map(|r| video_code::Region {+ x0: r.x0 / size.0 as f64,+ x1: r.x1 / size.0 as f64,+ y0: r.y0 / size.1 as f64,+ y1: r.y1 / size.1 as f64,+ });+ let screen_colour = (frames.len() % LAYOUT_SAMPLE_EVERY == 0)+ .then(|| screen_colour(&picture.frame, &view))+ .flatten();frames.push(OutputFrame {pts_secs: picture.pts_secs,readout,hash: picture_hash(&picture.frame),+ size,+ camera_region,+ screen_colour,})}).unwrap_or_else(|e| panic!("decode {path:?}: {e:?}"));@@ -456,6 +596,147 @@ pub fn check_sequence(}}+/// Product contract for exported MP4s: a keyframe at least every+/// `DEFAULT_KEYFRAME_INTERVAL_SECS` (2 s, crates/enc-ffmpeg h264.rs), so+/// shared videos seek quickly.+pub const MAX_KEYFRAME_INTERVAL_SECS: f64 = 2.0;+/// Colour checks on a flat key-colour band (code values).+pub const COLOUR_LEVEL_TOLERANCE: f64 = 4.0;+pub const COLOUR_MATRIX_TOLERANCE: f64 = 2.0;++/// Presentation checks every export gets on top of frame identity: the+/// keyframe interval (MP4), camera mirroring (the code reads mirrored exactly+/// when the project mirrors the camera; the screen never is), and camera+/// placement (the camera's key region lies in the corner/edge the project+/// asks for).+pub fn check_presentation(+ case: &mut Case,+ config: &ProjectConfiguration,+ frames: &[OutputFrame],+ path: &Path,+ fps: u32,+ keyframes: bool,+) {+ if keyframes {+ match media::keyframe_times(path) {+ Err(e) => case.problem("error", format!("keyframes: {e}")),+ Ok(times) => {+ let end = frames.len() as f64 / f64::from(fps);+ let slack = 1.0 / f64::from(fps) + 1e-3;+ let mut previous = 0.0;+ let mut worst: Option<(f64, f64)> = None;+ if times.first().is_none_or(|&t| t > slack) {+ case.problem(+ "keyframes",+ format!("the first frame is not a keyframe (keyframes {times:?})"),+ );+ }+ for &t in times.iter().chain(std::iter::once(&end)) {+ let gap = t - previous;+ if gap > MAX_KEYFRAME_INTERVAL_SECS + slack+ && worst.is_none_or(|(_, g)| gap > g)+ {+ worst = Some((previous, gap));+ }+ previous = t;+ }+ if let Some((from, gap)) = worst {+ case.problem(+ "keyframes",+ format!(+ "{gap:.3} s without a keyframe from {from:.3} s (contract: at most {MAX_KEYFRAME_INTERVAL_SECS} s; {} keyframes in {end:.3} s)",+ times.len()+ ),+ );+ }+ }+ }+ }++ let mut wrong_mirror = Vec::new();+ for (i, frame) in frames.iter().enumerate() {+ for kind in StreamKind::ALL {+ if let video_code::Readout::Marker { mirrored, .. } = frame.readout.get(kind) {+ let expected = kind == StreamKind::Camera && config.camera.mirror;+ if *mirrored != expected {+ wrong_mirror.push((i, kind.name(), *mirrored));+ }+ }+ }+ }+ if !wrong_mirror.is_empty() {+ case.problem(+ "mirror",+ format!(+ "{} frames show a stream mirrored wrongly (camera mirror setting {}): first {:?}",+ wrong_mirror.len(),+ config.camera.mirror,+ &wrong_mirror[..wrong_mirror.len().min(5)]+ ),+ );+ }++ // Colour level: the screen's key colour must decode, under the stream's+ // own colour tag (what players use), to the source luma. (Its chroma+ // barely separates BT.601 from BT.709; `check_colour` covers the matrix+ // with a saturated colour.)+ let level: Vec<(usize, f64)> = frames+ .iter()+ .enumerate()+ .filter_map(|(i, frame)| {+ let colour = frame.screen_colour?;+ let [dy, _, _] = colour_error(&colour, StreamKind::Screen.key_rgb());+ (dy.abs() > COLOUR_LEVEL_TOLERANCE).then_some((i, dy))+ })+ .collect();+ if let Some((i, dy)) = level.first() {+ case.problem(+ "colour-level",+ format!(+ "screen key colour luma off by {dy:+.1} code values in {} sampled frames (first frame {i}; tolerance {COLOUR_LEVEL_TOLERANCE})",+ level.len()+ ),+ );+ }++ use cap_project::{CameraXPosition, CameraYPosition};+ let mut misplaced = Vec::new();+ for (i, frame) in frames.iter().enumerate() {+ let Some(r) = frame.camera_region else {+ continue;+ };+ let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);+ let x_ok = match config.camera.position.x {+ CameraXPosition::Left => cx < 0.5,+ CameraXPosition::Center => (cx - 0.5).abs() < 0.05,+ CameraXPosition::Right => cx > 0.5,+ };+ let y_ok = match config.camera.position.y {+ CameraYPosition::Top => cy < 0.5,+ CameraYPosition::Bottom => cy > 0.5,+ };+ if !(x_ok && y_ok) {+ misplaced.push((+ i,+ (cx * 1000.0).round() / 1000.0,+ (cy * 1000.0).round() / 1000.0,+ ));+ }+ }+ if !misplaced.is_empty() {+ case.problem(+ "layout",+ format!(+ "camera drawn away from its {:?}/{:?} position in {} sampled frames (frame, centre x, centre y as fractions): {:?}",+ config.camera.position.x,+ config.camera.position.y,+ misplaced.len(),+ &misplaced[..misplaced.len().min(5)]+ ),+ );+ }+}+pub fn finish(case: Case) {if let Err(message) = report::settle(case) {panic!("{message}");@@ -770,3 +1051,87 @@ pub fn check_requests(pub fn assert_passed(failures: Vec<String>) {assert!(failures.is_empty(), "{}", failures.join("\n"));}++/// Runs the editor's real-time playback loop (`cap_editor::Playback`: warm-up,+/// prefetch, frame cache, wall clock) from `start_frame` for `seconds` of wall+/// time and returns every frame it delivered, read with `expect(frame number)`+/// (so transition frames are read as blends).+/// Video only (`create_segments_without_audio`): the audio clock has its own+/// oracle. Dropped frames are normal under load; delivered ones must be right.+pub async fn realtime_playback(+ project: &Project,+ config: ProjectConfiguration,+ decoder: Decoder,+ resolution: (u32, u32),+ fps: u32,+ start_frame: u32,+ seconds: f64,+ expect: &dyn Fn(u32) -> cap_verify::model::FrameExpectation,+) -> Result<Vec<(u32, FrameReadout)>, String> {+ use std::sync::{Arc, Mutex};+ let meta = project.meta.studio_meta().ok_or("not studio")?.clone();+ let recordings = cap_rendering::ProjectRecordingsMeta::new(&project.path, &meta)?;+ let constants = Arc::new(+ cap_rendering::RenderVideoConstants::new(+ &recordings.segments,+ project.meta.clone(),+ meta.clone(),+ )+ .await+ .map_err(|e| format!("render constants: {e}"))?,+ );+ let segments = Arc::new(+ cap_editor::create_segments_without_audio(&project.meta, &meta, decoder == Decoder::Ffmpeg)+ .await?,+ );+ let layers_rx = cap_editor::start_renderer_layers_creation(&constants, &config);+ let layers_rx = cap_editor::finish_renderer_layers_creation(layers_rx).await;+ let delivered: Arc<Mutex<Vec<cap_rendering::RenderedFrame>>> = Default::default();+ let sink = delivered.clone();+ let frame_cb: cap_editor::EditorFrameCallback = Box::new(move |output, _| {+ if let cap_editor::EditorFrameOutput::Rgba(frame) = output {+ sink.lock().unwrap().push(frame);+ }+ });+ let renderer = Arc::new(cap_editor::Renderer::spawn(+ constants.clone(),+ frame_cb,+ layers_rx,+ )?);+ let (_project_tx, project_rx) = tokio::sync::watch::channel(config);+ let (audio_output, _audio_sink) = cap_editor::AudioOutput::new_offline();+ let playback = cap_editor::Playback {+ renderer,+ render_constants: constants,+ start_frame_number: start_frame,+ project: project_rx,+ segment_medias: segments,+ music: cap_editor::MusicTracks::new(),+ audio_output: Arc::new(audio_output),+ telemetry: None,+ };+ let handle = playback+ .start(fps, XY::new(resolution.0, resolution.1))+ .await+ .map_err(|e| format!("playback start: {e:?}"))?;+ tokio::time::sleep(std::time::Duration::from_secs_f64(seconds)).await;+ handle.stop();+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;+ let frames = std::mem::take(&mut *delivered.lock().unwrap());+ Ok(frames+ .into_iter()+ .map(|frame| {+ let view = video_code::PackedFrame {+ data: &frame.data,+ width: frame.width as usize,+ height: frame.height as usize,+ stride: frame.padded_bytes_per_row as usize,+ order: video_code::PixelOrder::Rgba,+ };+ (+ frame.frame_number,+ read_expecting(&view, &expect(frame.frame_number)),+ )+ })+ .collect())+}diff --git a/crates/verify/tests/export.rs b/crates/verify/tests/export.rsindex 1dc93d99f..d3de58653 100644--- a/crates/verify/tests/export.rs+++ b/crates/verify/tests/export.rs@@ -3,7 +3,7 @@mod common;-use cap_project::{ProjectConfiguration, SceneMode, SceneSegment};+use cap_project::{ProjectConfiguration, SceneMode, SceneSegment, XY};use cap_verify::{catalog,fixture::FixtureSpec,@@ -95,6 +95,14 @@ fn run_project(&model,&frames,fps,+ format != Format::Mov,+ );+ common::check_presentation(+ &mut case,+ &config,+ &frames,+ &path,+ fps,format == Format::Mp4,);if determinism {@@ -175,6 +183,42 @@ fn hide_camera_scene(config: &mut ProjectConfiguration) {});}+/// A camera offset the user set on the clip (not auto-calculated): the camera+/// shows the frame `0.3 s` later than the screen's.+fn camera_user_offset(config: &mut ProjectConfiguration) {+ match config.clips.iter_mut().find(|c| c.index == 0) {+ Some(clip) => {+ clip.offsets.camera = 0.3;+ clip.offsets_auto_calculated = false;+ }+ None => config.clips.push(cap_project::ClipConfiguration {+ index: 0,+ offsets: cap_project::ClipOffsets {+ camera: 0.3,+ ..Default::default()+ },+ offsets_auto_calculated: false,+ }),+ }+}++#[test]+fn camera_offset() {+ let mut failures: Vec<String> = Vec::new();+ failures.extend(run(+ catalog::basic(report::tier()),+ &[Variant {+ edit: "camera-user-offset",+ apply: camera_user_offset,+ }],+ &[(Format::Mp4, 30)],+ &Decoder::all(),+ RES,+ false,+ ));+ common::assert_passed(failures);+}+#[test]fn basic() {let mut failures: Vec<String> = Vec::new();@@ -935,3 +979,316 @@ fn colour() {}common::assert_passed(failures);}++/// Background crop: the export must show the cropped part of the screen.+/// Frame identity alone cannot see a crop (the code is still readable when+/// the crop is ignored), so the screen code's square is located in every+/// tenth frame (the low-chroma block inside the screen's key region) and+/// must sit where the crop puts it.+#[test]+fn crop() {+ use cap_project::Crop;+ use cap_verify::{+ media,+ video_code::{self, PixelSource, StreamKind},+ };+ let spec = catalog::basic(report::tier());+ let id = case_id(&spec.name, "crop", Format::Mp4, 30, Decoder::Default);+ if !report::selected(&id) {+ return;+ }+ let project = common::project(&spec);+ let (src_w, src_h) = (f64::from(catalog::SCREEN_W), f64::from(catalog::SCREEN_H));+ let crop = Crop {+ position: XY::new(20, 10),+ size: XY::new(256, 144),+ };+ let mut config = project.config();+ config.camera.hide = true;+ config.background.crop = Some(crop.clone());+ let model = project.model(&config);+ let mut case = Case::new(&id);+ let dir = common::scratch_dir(&id);+ let run = ExportRun {+ fps: 30,+ resolution: RES,+ format: Format::Mp4,+ decoder: Decoder::Default,+ };+ let out = dir.path().join("a.mp4");+ match common::runtime().block_on(common::export(&project, config.clone(), &run, &out)) {+ Err(e) => case.problem("error", format!("export failed: {e}")),+ Ok(path) => {+ let mut frames = Vec::new();+ let (cx0, cy0) = (f64::from(crop.position.x), f64::from(crop.position.y));+ let (cw, ch) = (f64::from(crop.size.x), f64::from(crop.size.y));+ let side = StreamKind::Screen.code_side_fraction() * src_h;+ let mut misplaced = Vec::new();+ let mut index = 0usize;+ let decoded = media::decode_video(&path, |picture| {+ let i = index;+ index += 1;+ let view = picture.view();+ let region = video_code::locate_region(&view, StreamKind::Screen);+ let expected = region.map(|region| {+ let (rw, rh) = (region.x1 - region.x0, region.y1 - region.y0);+ (+ region.x0 + (src_w / 2.0 - cx0) / cw * rw,+ region.y0 + (src_h / 2.0 - cy0) / ch * rh,+ side / ch * rh,+ )+ });+ // The code is off the screen region's centre, so it is read+ // where the crop puts it.+ let screen = match expected {+ Some((x, y, s)) => {+ video_code::read_code_near(&view, StreamKind::Screen, x, y, s)+ }+ None => video_code::Readout::Absent,+ };+ frames.push(common::OutputFrame {+ pts_secs: picture.pts_secs,+ readout: video_code::FrameReadout {+ screen,+ camera: video_code::read_stream(&view, StreamKind::Camera),+ },+ hash: 0,+ size: (view.width(), view.height()),+ camera_region: None,+ screen_colour: None,+ });+ if i % common::LAYOUT_SAMPLE_EVERY != 0 {+ return;+ }+ let (Some(region), Some((expect_cx, expect_cy, expect_side))) = (region, expected)+ else {+ misplaced.push(format!("frame {i}: no screen region"));+ return;+ };+ let rh = region.y1 - region.y0;+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+ for y in (region.y0.ceil() as usize)..(region.y1 as usize).min(view.height()) {+ for x in (region.x0.ceil() as usize)..(region.x1 as usize).min(view.width()) {+ let (cb, cr) = view.chroma(x, y);+ if cb.hypot(cr) < 16.0 {+ x0 = x0.min(x as f64);+ y0 = y0.min(y as f64);+ x1 = x1.max(x as f64 + 1.0);+ y1 = y1.max(y as f64 + 1.0);+ }+ }+ }+ let tolerance = 0.03 * rh;+ let (cx, cy, s) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, y1 - y0);+ if x1 < x0+ || (cx - expect_cx).abs() > tolerance+ || (cy - expect_cy).abs() > tolerance+ || (s - expect_side).abs() > tolerance+ {+ misplaced.push(format!(+ "frame {i}: code square centre ({cx:.1}, {cy:.1}) side {s:.1}, crop puts it at ({expect_cx:.1}, {expect_cy:.1}) side {expect_side:.1}"+ ));+ }+ });+ if let Err(e) = decoded {+ case.problem("error", format!("decode: {e:?}"));+ }+ common::check_sequence(&mut case, &model, &frames, 30, true);+ if !misplaced.is_empty() {+ case.problem(+ "layout",+ format!(+ "cropped screen misplaced in {} sampled frames: {}",+ misplaced.len(),+ misplaced[..misplaced.len().min(3)].join("; ")+ ),+ );+ }+ }+ }+ common::finish(case);+}++/// Audio of a Studio project recorded through the real recording pipeline:+/// every marker the synthetic mic and loopback system audio emitted (at a+/// known time on the same clock as the screen frames) must be heard once in+/// the export, in sync with the screen frame emitted at the same time. This+/// checks the recording pipeline's audio timestamps (anchoring, gap filling,+/// start times in recording-meta) end to end; the audio oracle's own fixtures+/// are written with exact timing and never pass through the recorder.+#[test]+fn recorded_studio_audio() {+ use cap_verify::{+ audio_code::{self, AudioSource, MARKER_SECS},+ media,+ video_code::StreamKind,+ };+ let spec = catalog::recorded_studio(report::tier());+ let id = case_id(+ &format!("rec-{}", spec.name),+ "full-audio",+ Format::Mp4,+ 30,+ Decoder::Default,+ );+ if !report::selected(&id) {+ return;+ }+ let project = common::recorded(&spec);+ let mut case = Case::new(&id);+ let dir = common::scratch_dir(&id);+ let run = ExportRun {+ fps: 30,+ resolution: RES,+ format: Format::Mp4,+ decoder: Decoder::Default,+ };+ let out = dir.path().join("a.mp4");+ match common::runtime().block_on(common::export(&project, project.config(), &run, &out)) {+ Err(e) => case.problem("error", format!("export failed: {e}")),+ Ok(path) => {+ let frames = common::read_output(&path, None);+ match media::decode_audio(&path, Some(48_000)) {+ Err(e) => case.problem("error", format!("decode audio: {e:?}")),+ Ok(decoded) => {+ let mut mono = decoded.mono();+ let lead = (decoded.start_secs * 48_000.0).round() as i64;+ if lead > 0 {+ let mut padded = vec![0.0; lead as usize];+ padded.extend_from_slice(&mono);+ mono = padded;+ } else if lead < 0 {+ mono.drain(..(-lead as usize).min(mono.len()));+ }+ let frame = 1.0 / 30.0;+ let mut missing = Vec::new();+ let mut doubled = Vec::new();+ let mut off = Vec::new();+ let mut checked = 0;+ for (source, emitted_from) in [+ (+ AudioSource::Mic,+ spec.segments+ .iter()+ .map(|s| s.mic_delay)+ .collect::<Vec<_>>(),+ ),+ (+ AudioSource::System,+ spec.segments+ .iter()+ .map(|s| s.system_audio.then_some(0.0))+ .collect(),+ ),+ ] {+ let heard = audio_code::locate_markers(&mono, 48_000, source);+ if std::env::var_os("CAP_VERIFY_DUMP_AUDIO").is_some() {+ for h in &heard {+ eprintln!(+ " heard {}: {:?} at {:.4}s gain {:.3}",+ source.name(),+ h.index,+ h.time_secs,+ h.gain+ );+ }+ let file = project.path.join("content/segments/segment-0").join(+ if source == AudioSource::Mic {+ "audio-input.ogg"+ } else {+ "system_audio.ogg"+ },+ );+ if let Ok(src) = media::decode_audio(&file, Some(48_000)) {+ for h in audio_code::locate_markers(&src.mono(), 48_000, source) {+ eprintln!(+ " file {}: {:?} at {:.4}s (+{:.4}) gain {:.3}",+ source.name(),+ h.index,+ h.time_secs,+ src.start_secs,+ h.gain+ );+ }+ }+ }+ for (clip, segment) in spec.segments.iter().enumerate() {+ let Some(from) = emitted_from[clip] else {+ continue;+ };+ let schedule = audio_code::standard_schedule(+ source,+ 0.1,+ segment.duration - 0.1,+ 0.5,+ );+ for placement in schedule {+ let t = placement.time_secs;+ if t < from || t + MARKER_SECS > segment.duration - 0.05 {+ continue;+ }+ let slot = (t * 30.0).floor() as u32;+ let Some(shown) = frames.iter().position(|f| {+ f.readout.get(StreamKind::Screen).marker().is_some_and(|m| {+ usize::from(m.segment) == clip && m.index == slot+ })+ }) else {+ continue;+ };+ let shown_at = shown as f64 * frame;+ let hits: Vec<_> = heard+ .iter()+ .filter(|h| {+ h.index == Some(placement.index)+ && (h.time_secs - shown_at).abs() < 1.0+ })+ .collect();+ let what = format!(+ "{} #{} (clip {clip}, {t:.3} s)",+ source.name(),+ placement.index+ );+ match hits.as_slice() {+ [] => missing.push(what),+ [h] => {+ checked += 1;+ let av = h.time_secs - shown_at;+ if av.abs() > frame + 0.005 {+ off.push(format!("{what} {:+.1} ms", av * 1000.0));+ }+ }+ _ => doubled.push(what),+ }+ }+ }+ }+ if !missing.is_empty() || !doubled.is_empty() {+ case.problem(+ "audio",+ format!(+ "recorded markers: {} missing (first {:?}), {} heard twice (first {:?})",+ missing.len(),+ missing.first(),+ doubled.len(),+ doubled.first()+ ),+ );+ }+ if !off.is_empty() {+ case.problem(+ "sync",+ format!(+ "{} of {checked} recorded markers out of sync with the screen frame emitted with them (limit one frame + 5 ms): {}",+ off.len(),+ off[..off.len().min(3)].join("; ")+ ),+ );+ } else {+ case.note(format!("{checked} recorded markers in sync"));+ }+ }+ }+ }+ }+ common::finish(case);+}diff --git a/crates/verify/tests/playback.rs b/crates/verify/tests/playback.rsindex 94c419af6..3b0bbd1b9 100644--- a/crates/verify/tests/playback.rs+++ b/crates/verify/tests/playback.rs@@ -9,7 +9,7 @@ use cap_project::ProjectConfiguration;use cap_verify::{catalog,fixture::{FixtureSpec, Rng},- report::{self, Tier},+ report::{self, Case, Tier},};use common::Decoder;@@ -238,3 +238,71 @@ fn edits_sequential() {}common::assert_passed(failures);}++/// The real-time playback loop (`cap_editor::Playback`), not just the decode+/// and render path: every frame it delivers must show what the model puts at+/// that frame number. Frames may be dropped under load (macOS CI presents at+/// a few fps); at least `MIN_DELIVERED` must arrive.+#[test]+fn realtime_loop() {+ const MIN_DELIVERED: usize = 8;+ let rt = common::runtime();+ let mut failures = Vec::new();+ let project = common::project(&catalog::basic(report::tier()));+ for (edit, apply, start_fraction) in [+ ("full", no_edit as fn(&mut ProjectConfiguration), 0.0),+ ("cuts-speeds-reorder", cuts, 0.25),+ ("transition", transition, 0.2),+ ] {+ for decoder in Decoder::all() {+ let id = format!(+ "playback/{}/{edit}/realtime30-from{:.0}/{}",+ project.name,+ start_fraction * 100.0,+ decoder.label()+ );+ if !report::selected(&id) {+ continue;+ }+ let mut config = project.config();+ apply(&mut config);+ let model = project.model(&config);+ let total = model.output_frames(30);+ let first = (f64::from(total) * start_fraction) as u32;+ let seconds = f64::from(total - first) / 30.0 + 0.5;+ let mut case = Case::new(&id);+ match rt.block_on(common::realtime_playback(+ &project,+ config,+ decoder,+ RES,+ 30,+ first,+ seconds,+ &|f| model.expect(f, 30),+ )) {+ Err(e) => case.problem("error", e),+ Ok(delivered) => {+ let delivered: Vec<_> =+ delivered.into_iter().filter(|(f, _)| *f < total).collect();+ if delivered.len() < MIN_DELIVERED {+ case.problem(+ "dropped",+ format!(+ "real-time playback delivered {} frames, expected at least {MIN_DELIVERED}",+ delivered.len()+ ),+ );+ }+ let frames: Vec<u32> = delivered.iter().map(|(f, _)| *f).collect();+ let readouts: Vec<_> = delivered.into_iter().map(|(_, r)| r).collect();+ common::check_requests(&mut case, &model, &frames, &readouts, 30);+ }+ }+ if let Err(message) = report::settle(case) {+ failures.push(message);+ }+ }+ }+ common::assert_passed(failures);+}