Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(verify): fixtures, reference timeline model, oracle report and export tests

Richie McIlroy9a379e716378
diff --git a/crates/verify/expectations.txt b/crates/verify/expectations.txt
new file mode 100644
index 000000000..e69de29bb
diff --git a/crates/verify/src/catalog.rs b/crates/verify/src/catalog.rs
new file mode 100644
index 000000000..eb16e7a9c
--- /dev/null
+++ b/crates/verify/src/catalog.rs
@@ -0,0 +1,209 @@
+//! The fixture catalogue. Sizes and lengths depend on the tier: the fast
+//! tier keeps every fixture a few seconds long at 320x180 or below; the full
+//! tier lengthens the cases whose bugs need time to build up.
+
+use crate::{
+ audio_code::AudioSource,
+ fixture::{AudioTrackSpec, FixtureSpec, SegmentSpec, Timing, VideoTrackSpec},
+ report::Tier,
+};
+
+pub const SCREEN_W: u32 = 320;
+pub const SCREEN_H: u32 = 180;
+pub const CAMERA_W: u32 = 160;
+pub const CAMERA_H: u32 = 120;
+
+fn screen(fps: u32, timing: Timing) -> VideoTrackSpec {
+ VideoTrackSpec::new(SCREEN_W, SCREEN_H, fps, timing)
+}
+
+fn camera(timing: Timing) -> VideoTrackSpec {
+ VideoTrackSpec::new(CAMERA_W, CAMERA_H, 30, timing)
+}
+
+fn audio(source: AudioSource, duration: f64) -> AudioTrackSpec {
+ AudioTrackSpec {
+ source,
+ sample_rate: 48_000,
+ channels: if source == AudioSource::System { 2 } else { 1 },
+ duration,
+ start_time: 0.0,
+ }
+}
+
+/// Screen + camera + mic + system audio, constant 30 fps.
+pub fn basic(_tier: Tier) -> FixtureSpec {
+ let duration = 6.0;
+ FixtureSpec {
+ name: "basic".into(),
+ segments: vec![SegmentSpec {
+ display: screen(30, Timing::Constant { duration }),
+ camera: Some(camera(Timing::Constant { duration })),
+ mic: Some(audio(AudioSource::Mic, duration)),
+ system_audio: Some(audio(AudioSource::System, duration)),
+ }],
+ }
+}
+
+/// VFR screen with static holds longer than the decoders' frame cache
+/// (2.6 s and 4.2 s at 30 fps > 90 frames) plus a narrow 0.4 s hold, and a
+/// 60 fps nominal rate so holds are wide on the request grid.
+pub fn vfr_holds(_tier: Tier) -> FixtureSpec {
+ let duration = 14.0;
+ FixtureSpec {
+ name: "vfr-holds".into(),
+ segments: vec![SegmentSpec {
+ display: screen(
+ 60,
+ Timing::Holds {
+ duration,
+ holds: vec![(1.0, 2.6), (5.0, 0.4), (7.0, 4.2)],
+ },
+ ),
+ camera: Some(camera(Timing::Constant { duration })),
+ mic: None,
+ system_audio: None,
+ }],
+ }
+}
+
+/// Camera nominally 30 fps delivering ~12 fps with jitter, as real webcams
+/// do in low light. Long enough for the decoder's gap tracking to fill up.
+pub fn jitter_camera(tier: Tier) -> FixtureSpec {
+ let duration = match tier {
+ Tier::Fast => 40.0,
+ Tier::Full => 120.0,
+ };
+ FixtureSpec {
+ name: format!("jitter-camera-{duration:.0}s"),
+ segments: vec![SegmentSpec {
+ display: screen(30, Timing::Constant { duration }),
+ camera: Some(camera(Timing::Jittery {
+ duration,
+ seed: 0x5EED_0001,
+ holds: Vec::new(),
+ })),
+ mic: None,
+ system_audio: None,
+ }],
+ }
+}
+
+/// Screen at 30 fps with keyframes every 25 frames (0.833 s: never on a
+/// 10 ms grid), for seek-to-keyframe exactness.
+pub fn seek_gop(_tier: Tier) -> FixtureSpec {
+ let duration = 12.0;
+ let mut display = screen(30, Timing::Constant { duration });
+ display.gop = 25;
+ let mut cam = camera(Timing::Constant { duration });
+ cam.gop = 25;
+ FixtureSpec {
+ name: "seek-gop".into(),
+ segments: vec![SegmentSpec {
+ display,
+ camera: Some(cam),
+ mic: None,
+ system_audio: None,
+ }],
+ }
+}
+
+/// Camera that starts 1.5 s after the screen (it is the latest track).
+pub fn late_camera(_tier: Tier) -> FixtureSpec {
+ let duration = 6.0;
+ let mut cam = camera(Timing::Constant { duration: 4.5 });
+ cam.start_time = 1.5;
+ FixtureSpec {
+ name: "late-camera".into(),
+ segments: vec![SegmentSpec {
+ display: screen(30, Timing::Constant { duration }),
+ camera: Some(cam),
+ mic: None,
+ system_audio: None,
+ }],
+ }
+}
+
+/// Camera that starts before a slow microphone: the mic is the latest track,
+/// so the camera needs a positive alignment offset.
+pub fn early_camera(_tier: Tier) -> FixtureSpec {
+ let duration = 6.0;
+ let mut display = screen(30, Timing::Constant { duration });
+ display.start_time = 0.2;
+ let mut cam = camera(Timing::Constant { duration });
+ cam.start_time = 0.0;
+ let mut mic = audio(AudioSource::Mic, duration - 1.0);
+ mic.start_time = 1.0;
+ FixtureSpec {
+ name: "early-camera".into(),
+ segments: vec![SegmentSpec {
+ display,
+ camera: Some(cam),
+ mic: Some(mic),
+ system_audio: None,
+ }],
+ }
+}
+
+/// Camera file whose pts start 2 s in (frames before that do not exist).
+pub fn camera_pts_late(_tier: Tier) -> FixtureSpec {
+ let duration = 6.0;
+ let mut cam = camera(Timing::Constant { duration: 4.0 });
+ cam.pts_offset = 2.0;
+ FixtureSpec {
+ name: "camera-pts-late".into(),
+ segments: vec![SegmentSpec {
+ display: screen(30, Timing::Constant { duration }),
+ camera: Some(cam),
+ mic: None,
+ system_audio: None,
+ }],
+ }
+}
+
+/// Two recording segments (pause/resume), the second without a camera.
+pub fn multi_segment(_tier: Tier) -> FixtureSpec {
+ FixtureSpec {
+ name: "multi-segment".into(),
+ segments: vec![
+ SegmentSpec {
+ display: screen(30, Timing::Constant { duration: 4.0 }),
+ camera: Some(camera(Timing::Constant { duration: 4.0 })),
+ mic: None,
+ system_audio: None,
+ },
+ SegmentSpec {
+ display: screen(30, Timing::Constant { duration: 3.0 }),
+ camera: None,
+ mic: None,
+ system_audio: None,
+ },
+ ],
+ }
+}
+
+/// A jittery 60 fps-nominal screen (~25 fps delivered, so nearly every
+/// frame interval is a hole on the request grid) with a 10 s static hold at
+/// 30-40 s. Timelines that play past the hold, then elsewhere, then jump
+/// back into it exercise the decoders' bounded hole tracking.
+pub fn backward_hold(_tier: Tier) -> FixtureSpec {
+ let duration = 52.0;
+ let mut display = screen(
+ 60,
+ Timing::Jittery {
+ duration,
+ seed: 0x5EED_0002,
+ holds: vec![(30.0, 10.0)],
+ },
+ );
+ display.gop = 30;
+ FixtureSpec {
+ name: "backward-hold".into(),
+ segments: vec![SegmentSpec {
+ display,
+ camera: Some(camera(Timing::Constant { duration })),
+ mic: None,
+ system_audio: None,
+ }],
+ }
+}
diff --git a/crates/verify/src/fixture.rs b/crates/verify/src/fixture.rs
new file mode 100644
index 000000000..1593a2947
--- /dev/null
+++ b/crates/verify/src/fixture.rs
@@ -0,0 +1,526 @@
+//! Fixture projects. Every fixture is generated by code from a spec and a
+//! seed; nothing binary is checked in.
+//!
+//! Two generators share the project layout:
+//! - [`write_fixture`] writes tracks directly with exact presentation times.
+//! It is fast and deterministic and is how exotic timing is produced: VFR
+//! holds of several seconds, jittery cameras, late starts.
+//! - [`crate::pipeline`] records through the real recording pipeline in real
+//! time (channel sources -> mux loop -> encoders -> containers).
+//!
+//! Source truth is never taken from the spec: [`SourceTruth::read`] decodes
+//! every written track and reads each frame's marker and presentation time.
+
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, bail};
+use cap_project::{
+ AudioMeta, BackgroundSource, ClipConfiguration, MultipleSegment, MultipleSegments, Platform,
+ ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta,
+ StudioRecordingStatus, TimelineConfiguration, TimelineSegment, VideoMeta,
+};
+use relative_path::RelativePathBuf;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ audio_code::{self, AudioSource},
+ media::{self, AudioCodec, VideoWriter, VideoWriterConfig},
+ video_code::{self, FrameMarker, StreamKind},
+};
+
+/// Bump when generated output changes so cached fixtures are rebuilt.
+pub const GENERATOR_VERSION: u32 = 1;
+
+/// splitmix64: tiny deterministic PRNG; every fixture prints its seed.
+#[derive(Clone)]
+pub struct Rng(u64);
+
+impl Rng {
+ pub fn new(seed: u64) -> Self {
+ Self(seed)
+ }
+
+ pub fn next_u64(&mut self) -> u64 {
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
+ let mut z = self.0;
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+ }
+
+ pub fn f64(&mut self) -> f64 {
+ (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
+ }
+
+ pub fn range(&mut self, lo: u64, hi: u64) -> u64 {
+ lo + self.next_u64() % (hi - lo + 1)
+ }
+}
+
+/// Source frame slots on the nominal grid: frame `k` is presented at
+/// `k / fps`. Slot numbers double as marker indices, so a report saying
+/// "source frame 1797" also says "59.9 s into the track at 30 fps".
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub enum Timing {
+ /// Every slot from 0 to `duration * fps`.
+ Constant { duration: f64 },
+ /// Constant rate with no frames inside the given (start, length) holds,
+ /// like a static screen under VFR capture.
+ Holds { duration: f64, holds: Vec<(f64, f64)> },
+ /// A source delivering below its nominal rate with jitter: consecutive
+ /// frames are 1..=4 slots apart (mean ~2.4), with a rare 6..=12 slot
+ /// stall, and no frames inside `holds`.
+ Jittery {
+ duration: f64,
+ seed: u64,
+ holds: Vec<(f64, f64)>,
+ },
+ /// Explicit slots.
+ Slots(Vec<u32>),
+}
+
+impl Timing {
+ pub fn slots(&self, fps: u32) -> Vec<u32> {
+ match self {
+ Timing::Constant { duration } => (0..(duration * f64::from(fps)).round() as u32).collect(),
+ Timing::Holds { duration, holds } => (0..(duration * f64::from(fps)).round() as u32)
+ .filter(|&k| {
+ let t = f64::from(k) / f64::from(fps);
+ !holds.iter().any(|&(s, l)| t > s && t < s + l)
+ })
+ .collect(),
+ Timing::Jittery {
+ duration,
+ seed,
+ holds,
+ } => {
+ let mut rng = Rng::new(*seed);
+ let end = (duration * f64::from(fps)).round() as u32;
+ let mut out = Vec::new();
+ let mut k = 0;
+ while k < end {
+ let t = f64::from(k) / f64::from(fps);
+ if !holds.iter().any(|&(s, l)| t > s && t < s + l) {
+ out.push(k);
+ }
+ let r = rng.f64();
+ k += if r < 0.02 {
+ rng.range(6, 12) as u32
+ } else if r < 0.17 {
+ 1
+ } else if r < 0.62 {
+ 2
+ } else if r < 0.87 {
+ 3
+ } else {
+ 4
+ };
+ }
+ out
+ }
+ Timing::Slots(slots) => slots.clone(),
+ }
+ }
+
+ pub fn duration(&self, fps: u32) -> f64 {
+ match self {
+ Timing::Constant { duration }
+ | Timing::Holds { duration, .. }
+ | Timing::Jittery { duration, .. } => *duration,
+ Timing::Slots(slots) => {
+ f64::from(slots.last().copied().unwrap_or(0) + 1) / f64::from(fps)
+ }
+ }
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct VideoTrackSpec {
+ pub width: u32,
+ pub height: u32,
+ pub fps: u32,
+ pub timing: Timing,
+ /// Frames between keyframes. Pick values whose keyframe times are not on
+ /// a 10 ms grid to exercise seek rounding.
+ pub gop: u32,
+ pub b_frames: u32,
+ /// Presentation time of the first slot inside the file (0 for every real
+ /// recording; non-zero models a file whose pts start late).
+ pub pts_offset: f64,
+ /// `start_time` written to recording-meta.json.
+ pub start_time: f64,
+}
+
+impl VideoTrackSpec {
+ pub fn new(width: u32, height: u32, fps: u32, timing: Timing) -> Self {
+ Self {
+ width,
+ height,
+ fps,
+ timing,
+ gop: fps * 2 + 1,
+ b_frames: 0,
+ pts_offset: 0.0,
+ start_time: 0.0,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct AudioTrackSpec {
+ pub source: AudioSource,
+ pub sample_rate: u32,
+ pub channels: u16,
+ pub duration: f64,
+ pub start_time: f64,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct SegmentSpec {
+ pub display: VideoTrackSpec,
+ pub camera: Option<VideoTrackSpec>,
+ pub mic: Option<AudioTrackSpec>,
+ pub system_audio: Option<AudioTrackSpec>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
+pub struct FixtureSpec {
+ pub name: String,
+ pub segments: Vec<SegmentSpec>,
+}
+
+impl FixtureSpec {
+ /// Stable key over the spec and generator version, for caching.
+ pub fn cache_key(&self) -> String {
+ let json = serde_json::to_string(self).unwrap_or_default();
+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325 ^ u64::from(GENERATOR_VERSION);
+ for byte in json.bytes() {
+ hash ^= u64::from(byte);
+ hash = hash.wrapping_mul(0x0100_0000_01b3);
+ }
+ format!("{}-{hash:016x}", self.name)
+ }
+}
+
+pub(crate) fn segment_dir(i: usize) -> String {
+ format!("content/segments/segment-{i}")
+}
+
+fn write_video_track(
+ path: &Path,
+ kind: StreamKind,
+ segment: u8,
+ spec: &VideoTrackSpec,
+) -> anyhow::Result<()> {
+ let mut config = VideoWriterConfig::new(spec.width, spec.height, spec.fps);
+ config.gop = spec.gop;
+ config.b_frames = spec.b_frames;
+ let mut writer = VideoWriter::create(path, &config)?;
+ for slot in spec.timing.slots(spec.fps) {
+ let marker = FrameMarker::new(kind, segment, slot);
+ let rgba = video_code::marker_rgba(marker, spec.width as usize, spec.height as usize);
+ writer.write_rgba(&rgba, spec.pts_offset + f64::from(slot) / f64::from(spec.fps))?;
+ }
+ writer.finish()?;
+ Ok(())
+}
+
+fn write_audio_track(path: &Path, spec: &AudioTrackSpec) -> anyhow::Result<()> {
+ let samples = (spec.duration * f64::from(spec.sample_rate)).round() as usize;
+ let mut mono = vec![0.0f32; samples];
+ let schedule = audio_code::standard_schedule(spec.source, 0.1, spec.duration - 0.1, 0.5);
+ audio_code::render_markers(
+ &mut mono,
+ spec.sample_rate,
+ spec.source,
+ &schedule,
+ audio_code::DEFAULT_AMPLITUDE,
+ );
+ let channels = vec![mono; usize::from(spec.channels.max(1))];
+ media::write_audio(path, &channels, spec.sample_rate, AudioCodec::Opus, 96_000)
+}
+
+/// Writes recording-meta.json and a default project-config.json for the
+/// given segments and returns the meta.
+pub fn write_project_files(
+ dir: &Path,
+ name: &str,
+ segments: Vec<MultipleSegment>,
+) -> anyhow::Result<RecordingMeta> {
+ let mut timeline = Vec::new();
+ let mut clips = Vec::new();
+ for (i, segment) in segments.iter().enumerate() {
+ let display = dir.join(segment.display.path.as_str());
+ let duration = media::video_packet_times(&display)?
+ .last()
+ .copied()
+ .unwrap_or(0.0)
+ + 1.0 / f64::from(segment.display.fps);
+ timeline.push(TimelineSegment {
+ recording_clip: i as u32,
+ start: 0.0,
+ end: duration,
+ timescale: 1.0,
+ name: None,
+ speed_audio_mode: None,
+ hide_cursor: None,
+ volume: None,
+ });
+ clips.push(ClipConfiguration {
+ index: i as u32,
+ offsets: segment.calculate_audio_offsets(),
+ offsets_auto_calculated: true,
+ });
+ }
+ let meta = RecordingMeta {
+ platform: Some(Platform::default()),
+ project_path: dir.to_path_buf(),
+ pretty_name: name.to_string(),
+ sharing: None,
+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments,
+ cursors: Default::default(),
+ status: Some(StudioRecordingStatus::Complete),
+ },
+ })),
+ upload: None,
+ };
+ meta.save_for_project()
+ .map_err(|e| anyhow::anyhow!("save recording meta: {e:?}"))?;
+ let mut config = verification_project_config();
+ config.timeline = Some(TimelineConfiguration {
+ segments: timeline,
+ transitions: Vec::new(),
+ zoom_segments: Vec::new(),
+ scene_segments: Vec::new(),
+ style_segments: Vec::new(),
+ image_segments: Vec::new(),
+ mask_segments: Vec::new(),
+ text_segments: Vec::new(),
+ caption_segments: Vec::new(),
+ keyboard_segments: Vec::new(),
+ audio_segments: Vec::new(),
+ camera3d_segments: Vec::new(),
+ });
+ config.clips = clips;
+ config.write(dir)?;
+ Ok(meta)
+}
+
+/// Product defaults with a neutral background (never mistaken for a key
+/// colour) and no screen motion blur (which blends neighbouring frames).
+pub fn verification_project_config() -> ProjectConfiguration {
+ let mut config = ProjectConfiguration::default();
+ config.background.source = BackgroundSource::Color {
+ value: [60, 60, 60],
+ alpha: 255,
+ };
+ config.screen_motion_blur = 0.0;
+ config
+}
+
+/// Writes a fixture project with exact timing into `dir` (created).
+pub fn write_fixture(spec: &FixtureSpec, dir: &Path) -> anyhow::Result<()> {
+ if dir.exists() {
+ std::fs::remove_dir_all(dir)?;
+ }
+ let mut segments = Vec::new();
+ for (i, segment) in spec.segments.iter().enumerate() {
+ let seg_dir = segment_dir(i);
+ std::fs::create_dir_all(dir.join(&seg_dir))?;
+ let rel = |file: &str| RelativePathBuf::from(format!("{seg_dir}/{file}"));
+ write_video_track(
+ &dir.join(rel("display.mp4").as_str()),
+ StreamKind::Screen,
+ i as u8,
+ &segment.display,
+ )
+ .context("display track")?;
+ let camera = match &segment.camera {
+ Some(camera) => {
+ write_video_track(
+ &dir.join(rel("camera.mp4").as_str()),
+ StreamKind::Camera,
+ i as u8,
+ camera,
+ )
+ .context("camera track")?;
+ Some(VideoMeta {
+ path: rel("camera.mp4"),
+ fps: camera.fps,
+ start_time: Some(camera.start_time),
+ device_id: None,
+ })
+ }
+ None => None,
+ };
+ let audio = |spec: &Option<AudioTrackSpec>, file: &str| -> anyhow::Result<_> {
+ Ok(match spec {
+ Some(a) => {
+ write_audio_track(&dir.join(rel(file).as_str()), a)?;
+ Some(AudioMeta {
+ path: rel(file),
+ start_time: Some(a.start_time),
+ device_id: None,
+ gap_summary: None,
+ })
+ }
+ None => None,
+ })
+ };
+ let mic = audio(&segment.mic, "audio-input.ogg")?;
+ let system_audio = audio(&segment.system_audio, "system_audio.ogg")?;
+ segments.push(MultipleSegment {
+ display: VideoMeta {
+ path: rel("display.mp4"),
+ fps: segment.display.fps,
+ start_time: Some(segment.display.start_time),
+ device_id: None,
+ },
+ camera,
+ mic,
+ system_audio,
+ cursor: None,
+ keyboard: None,
+ display_notch: None,
+ });
+ }
+ write_project_files(dir, &spec.name, segments)?;
+ Ok(())
+}
+
+/// Root for generated fixtures: `CAP_VERIFY_FIXTURE_DIR`, else
+/// `<target>/verify-fixtures`. CI caches this directory keyed by the
+/// generator sources.
+pub fn fixture_root() -> PathBuf {
+ if let Some(dir) = std::env::var_os("CAP_VERIFY_FIXTURE_DIR") {
+ return PathBuf::from(dir);
+ }
+ let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ let target = std::env::var_os("CARGO_TARGET_DIR")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| manifest.join("../../target"));
+ target.join("verify-fixtures")
+}
+
+/// Returns a ready fixture, generating it unless a complete cached copy with
+/// the same key exists. Safe to call from parallel test processes.
+pub fn ensure_fixture(
+ spec: &FixtureSpec,
+ generate: impl FnOnce(&FixtureSpec, &Path) -> anyhow::Result<()>,
+) -> anyhow::Result<PathBuf> {
+ let root = fixture_root();
+ std::fs::create_dir_all(&root)?;
+ let key = spec.cache_key();
+ let dir = root.join(format!("{key}.cap"));
+ let done = root.join(format!("{key}.complete"));
+ if done.exists() && dir.exists() {
+ return Ok(dir);
+ }
+ let staging = root.join(format!("{key}.{}.tmp.cap", std::process::id()));
+ generate(spec, &staging)?;
+ // Paths inside recording-meta.json are relative, so the staged project
+ // stays valid after the rename.
+ if dir.exists() {
+ let _ = std::fs::remove_dir_all(&staging);
+ } else if let Err(error) = std::fs::rename(&staging, &dir) {
+ if !dir.exists() {
+ bail!("publish fixture {dir:?}: {error}");
+ }
+ let _ = std::fs::remove_dir_all(&staging);
+ }
+ std::fs::write(&done, key)?;
+ Ok(dir)
+}
+
+/// One decoded source frame: its presentation time in the file and marker.
+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
+pub struct SourceFrame {
+ pub pts_secs: f64,
+ pub index: u32,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct TrackTruth {
+ pub kind: StreamKind,
+ pub segment: u8,
+ /// Frames in presentation order.
+ pub frames: Vec<SourceFrame>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct SegmentTruth {
+ pub screen: TrackTruth,
+ pub camera: Option<TrackTruth>,
+}
+
+/// Ground truth for a project, read back from its files.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct SourceTruth {
+ pub segments: Vec<SegmentTruth>,
+}
+
+impl SourceTruth {
+ pub fn read(project: &Path) -> anyhow::Result<Self> {
+ let cache = project.join("verify-truth.json");
+ if let Ok(text) = std::fs::read_to_string(&cache)
+ && let Ok(truth) = serde_json::from_str(&text)
+ {
+ return Ok(truth);
+ }
+ let meta = RecordingMeta::load_for_project(project)
+ .map_err(|e| anyhow::anyhow!("load meta: {e:?}"))?;
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = meta.studio_meta() else {
+ bail!("not a multi-segment studio project");
+ };
+ let mut segments = Vec::new();
+ for (i, segment) in inner.segments.iter().enumerate() {
+ let screen = read_track(
+ &project.join(segment.display.path.as_str()),
+ StreamKind::Screen,
+ i as u8,
+ )?;
+ let camera = match &segment.camera {
+ Some(camera) => Some(read_track(
+ &project.join(camera.path.as_str()),
+ StreamKind::Camera,
+ i as u8,
+ )?),
+ None => None,
+ };
+ segments.push(SegmentTruth { screen, camera });
+ }
+ let truth = SourceTruth { segments };
+ let _ = std::fs::write(&cache, serde_json::to_string(&truth)?);
+ Ok(truth)
+ }
+}
+
+fn read_track(path: &Path, kind: StreamKind, segment: u8) -> anyhow::Result<TrackTruth> {
+ let mut frames = Vec::new();
+ let mut bad = Vec::new();
+ media::decode_video(path, |picture| {
+ match video_code::read_stream(&picture.view(), kind).marker() {
+ Some(marker) if marker.segment == segment => frames.push(SourceFrame {
+ pts_secs: picture.pts_secs,
+ index: marker.index,
+ }),
+ other => bad.push((picture.pts_secs, other)),
+ }
+ })?;
+ if !bad.is_empty() {
+ bail!(
+ "{path:?}: {} source frames without a readable {} marker (first at {:.3}s)",
+ bad.len(),
+ kind.name(),
+ bad[0].0
+ );
+ }
+ frames.sort_by(|a, b| a.pts_secs.total_cmp(&b.pts_secs));
+ Ok(TrackTruth {
+ kind,
+ segment,
+ frames,
+ })
+}
diff --git a/crates/verify/src/lib.rs b/crates/verify/src/lib.rs
index af3492ae9..e2c643d8a 100644
--- a/crates/verify/src/lib.rs
+++ b/crates/verify/src/lib.rs
@@ -5,3 +5,7 @@ pub mod audio_code;
pub mod media;
pub mod oracle;
pub mod video_code;
+pub mod catalog;
+pub mod fixture;
+pub mod model;
+pub mod report;
diff --git a/crates/verify/src/model.rs b/crates/verify/src/model.rs
new file mode 100644
index 000000000..830c82078
--- /dev/null
+++ b/crates/verify/src/model.rs
@@ -0,0 +1,403 @@
+//! Reference timeline model: what every output frame must show.
+//!
+//! Written for the tests from the project's documented rules, not by calling
+//! the production mapping:
+//! - Output frame `i` at `fps` is output time `i / fps`; an export has
+//! `ceil(fps * duration)` frames.
+//! - Timeline segments play back to back; segment `k` covers
+//! `(end - start) / timescale` output seconds and maps output time `u`
+//! inside it to recording time `start + u * timescale`. A clip transition
+//! into segment `k` overlaps the two segments by its (clamped) duration;
+//! frames inside a transition are a blend and are not checked.
+//! - Every track of a recording segment is aligned to the latest track start
+//! (`latest_start_time - track.start_time` is added to the request). The
+//! camera additionally takes the clip's camera offset when the user set it;
+//! an auto-calculated camera offset describes the same start alignment and
+//! must not be applied a second time.
+//! - A request at track time `s` asks for frame slot `floor(s * fps_meta)`,
+//! where `fps_meta` is the track's nominal rate from recording-meta.json,
+//! and is answered by the newest source frame whose slot
+//! `round(pts * fps_meta)` is at or before it (the first frame before the
+//! track starts). Requests within float rounding of a slot boundary accept
+//! either neighbour.
+//! - The camera is absent when hidden, when the segment has no camera, and
+//! inside a "hide camera" scene. A scene fades in over `transition_in`
+//! before its start and out over `transition_out` before its end; fades
+//! are not checked.
+
+use cap_project::{ProjectConfiguration, RecordingMeta, SceneMode, StudioRecordingMeta};
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ fixture::{SourceTruth, TrackTruth},
+ oracle::StreamExpectation,
+ video_code::StreamKind,
+};
+
+const MIN_TRANSITION: f64 = 0.05;
+const BOUNDARY_EPSILON: f64 = 1e-9;
+const SLOT_EPSILON: f64 = 2e-3;
+
+#[derive(Clone, Debug)]
+struct ModelSegment {
+ clip: usize,
+ start: f64,
+ end: f64,
+ timescale: f64,
+ transition_in: f64,
+}
+
+impl ModelSegment {
+ fn duration(&self) -> f64 {
+ (self.end - self.start) / self.timescale
+ }
+}
+
+#[derive(Clone, Debug)]
+struct TrackTiming {
+ fps: u32,
+ offset: f64,
+}
+
+#[derive(Clone, Debug)]
+struct ClipTiming {
+ screen: TrackTiming,
+ camera: Option<TrackTiming>,
+ user_camera_offset: f64,
+}
+
+#[derive(Clone, Copy, Debug)]
+enum SceneRule {
+ HideCamera,
+ Unchecked,
+}
+
+#[derive(Clone, Debug)]
+struct Scene {
+ start: f64,
+ end: f64,
+ fade_in: f64,
+ fade_out: f64,
+ rule: SceneRule,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct FrameExpectation {
+ pub screen: StreamExpectation,
+ pub camera: StreamExpectation,
+ /// (recording clip, recording time) the frame maps to, for reports.
+ pub source: Option<(usize, f64)>,
+}
+
+impl FrameExpectation {
+ pub fn get(&self, kind: StreamKind) -> &StreamExpectation {
+ match kind {
+ StreamKind::Screen => &self.screen,
+ StreamKind::Camera => &self.camera,
+ }
+ }
+}
+
+enum Mapping {
+ Single { segment: usize, source_time: f64 },
+ Transition,
+}
+
+pub struct ReferenceModel {
+ segments: Vec<ModelSegment>,
+ output_starts: Vec<f64>,
+ clips: Vec<ClipTiming>,
+ truth: SourceTruth,
+ camera_hidden: bool,
+ scenes: Vec<Scene>,
+ unsupported: Option<String>,
+}
+
+impl ReferenceModel {
+ pub fn new(
+ meta: &RecordingMeta,
+ project: &ProjectConfiguration,
+ truth: SourceTruth,
+ ) -> anyhow::Result<Self> {
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = meta.studio_meta() else {
+ anyhow::bail!("the model covers multi-segment studio projects");
+ };
+ let clips = inner
+ .segments
+ .iter()
+ .enumerate()
+ .map(|(i, segment)| {
+ let starts = [
+ segment.display.start_time,
+ segment.camera.as_ref().and_then(|c| c.start_time),
+ segment.mic.as_ref().and_then(|m| m.start_time),
+ segment.system_audio.as_ref().and_then(|s| s.start_time),
+ ];
+ let present = [
+ true,
+ segment.camera.is_some(),
+ segment.mic.is_some(),
+ segment.system_audio.is_some(),
+ ];
+ let all_known = starts
+ .iter()
+ .zip(present)
+ .all(|(start, present)| !present || start.is_some());
+ let latest = all_known.then(|| {
+ starts
+ .iter()
+ .flatten()
+ .copied()
+ .fold(f64::NEG_INFINITY, f64::max)
+ });
+ let align = |start: Option<f64>| match (latest, start) {
+ (Some(latest), Some(start)) => latest - start,
+ _ => 0.0,
+ };
+ let clip = project.clips.iter().find(|c| c.index as usize == i);
+ let user_camera_offset = clip
+ .filter(|c| !c.offsets_auto_calculated)
+ .map_or(0.0, |c| f64::from(c.offsets.camera));
+ ClipTiming {
+ screen: TrackTiming {
+ fps: segment.display.fps,
+ offset: align(segment.display.start_time),
+ },
+ camera: segment.camera.as_ref().map(|c| TrackTiming {
+ fps: c.fps,
+ offset: align(c.start_time),
+ }),
+ user_camera_offset,
+ }
+ })
+ .collect();
+ let timeline = project
+ .timeline
+ .as_ref()
+ .ok_or_else(|| anyhow::anyhow!("project has no timeline"))?;
+ let mut segments: Vec<ModelSegment> = timeline
+ .segments
+ .iter()
+ .map(|s| ModelSegment {
+ clip: s.recording_clip as usize,
+ start: s.start,
+ end: s.end,
+ timescale: s.timescale,
+ transition_in: 0.0,
+ })
+ .collect();
+ for transition in &timeline.transitions {
+ let k = transition.segment_index as usize;
+ if k == 0 || k >= segments.len() {
+ continue;
+ }
+ let max = segments[k - 1].duration().min(segments[k].duration()) / 2.0;
+ if transition.duration.is_finite() && transition.duration > 0.0 && max >= MIN_TRANSITION
+ {
+ segments[k].transition_in = transition.duration.clamp(MIN_TRANSITION, max);
+ }
+ }
+ let mut output_starts = Vec::with_capacity(segments.len());
+ let mut at = 0.0;
+ for (k, segment) in segments.iter().enumerate() {
+ output_starts.push(at);
+ let next_in = segments.get(k + 1).map_or(0.0, |n| n.transition_in);
+ at += segment.duration() - next_in;
+ }
+ let scenes = timeline
+ .scene_segments
+ .iter()
+ .filter(|s| !matches!(s.mode, SceneMode::Default))
+ .map(|s| Scene {
+ start: s.start,
+ end: s.end,
+ fade_in: s.transition_in.max(0.0),
+ fade_out: s.transition_out.max(0.0),
+ rule: if matches!(s.mode, SceneMode::HideCamera) {
+ SceneRule::HideCamera
+ } else {
+ SceneRule::Unchecked
+ },
+ })
+ .collect();
+ let unsupported = if timeline.text_segments.iter().any(|t| t.enabled) {
+ Some("text segments".to_string())
+ } else if !timeline.zoom_segments.is_empty() {
+ Some("zoom segments".to_string())
+ } else if !timeline.camera3d_segments.is_empty() {
+ Some("3D camera segments".to_string())
+ } else {
+ None
+ };
+ Ok(Self {
+ segments,
+ output_starts,
+ clips,
+ truth,
+ camera_hidden: project.camera.hide,
+ scenes,
+ unsupported,
+ })
+ }
+
+ pub fn duration(&self) -> f64 {
+ let total: f64 = self.segments.iter().map(ModelSegment::duration).sum();
+ total - self.segments.iter().map(|s| s.transition_in).sum::<f64>()
+ }
+
+ pub fn output_frames(&self, fps: u32) -> u32 {
+ (f64::from(fps) * self.duration()).ceil() as u32
+ }
+
+ fn map(&self, t: f64) -> Option<Mapping> {
+ for (k, segment) in self.segments.iter().enumerate() {
+ let start = self.output_starts[k];
+ let next_in = self.segments.get(k + 1).map_or(0.0, |n| n.transition_in);
+ if t >= start && t < start + segment.transition_in {
+ return Some(Mapping::Transition);
+ }
+ if t >= start + segment.transition_in && t < start + segment.duration() - next_in {
+ let elapsed = t - start;
+ if elapsed > segment.duration() {
+ return None;
+ }
+ return Some(Mapping::Single {
+ segment: k,
+ source_time: segment.start + elapsed * segment.timescale,
+ });
+ }
+ }
+ None
+ }
+
+ fn near_boundary(&self, t: f64) -> bool {
+ self.segments.iter().enumerate().any(|(k, segment)| {
+ let start = self.output_starts[k];
+ let edges = [
+ start,
+ start + segment.transition_in,
+ start + segment.duration(),
+ ];
+ edges.iter().any(|e| (t - e).abs() < BOUNDARY_EPSILON)
+ })
+ }
+
+ fn track(&self, clip: usize, kind: StreamKind) -> Option<(&TrackTruth, &TrackTiming)> {
+ let truth = self.truth.segments.get(clip)?;
+ let timing = self.clips.get(clip)?;
+ match kind {
+ StreamKind::Screen => Some((&truth.screen, &timing.screen)),
+ StreamKind::Camera => Some((truth.camera.as_ref()?, timing.camera.as_ref()?)),
+ }
+ }
+
+ /// Frames a decoder must answer for a request at recording time `time`
+ /// (before the track's own alignment offset).
+ pub fn answer(&self, clip: usize, kind: StreamKind, time: f64) -> StreamExpectation {
+ let Some((track, timing)) = self.track(clip, kind) else {
+ return StreamExpectation::Absent;
+ };
+ let mut request = time + timing.offset;
+ if kind == StreamKind::Camera {
+ request += self.clips[clip].user_camera_offset;
+ }
+ let x = request.max(0.0) * f64::from(timing.fps);
+ let nearest = x.round();
+ let slots: Vec<i64> = if (x - nearest).abs() < SLOT_EPSILON {
+ vec![nearest as i64 - 1, nearest as i64]
+ } else {
+ vec![x.floor() as i64]
+ };
+ let numbers: Vec<i64> = track
+ .frames
+ .iter()
+ .map(|f| (f.pts_secs * f64::from(timing.fps)).round() as i64)
+ .collect();
+ let mut allowed = Vec::new();
+ for slot in slots {
+ let upto = numbers.partition_point(|&n| n <= slot);
+ let target = if upto == 0 { numbers[0] } else { numbers[upto - 1] };
+ for (frame, &n) in track.frames.iter().zip(&numbers) {
+ if n == target && !allowed.contains(&frame.index) {
+ allowed.push(frame.index);
+ }
+ }
+ }
+ allowed.sort_unstable();
+ StreamExpectation::Frame {
+ segment: track.segment,
+ allowed,
+ }
+ }
+
+ fn scene_rule(&self, t: f64) -> Option<(SceneRule, bool)> {
+ self.scenes.iter().find_map(|scene| {
+ // A scene fades in before its start and out before its end.
+ if t < scene.start - scene.fade_in || t >= scene.end {
+ return None;
+ }
+ let fading = t < scene.start || t >= scene.end - scene.fade_out;
+ Some((scene.rule, fading))
+ })
+ }
+
+ pub fn expect_at(&self, t: f64) -> FrameExpectation {
+ let unchecked = |reason: &str| FrameExpectation {
+ screen: StreamExpectation::Unchecked {
+ reason: reason.into(),
+ },
+ camera: StreamExpectation::Unchecked {
+ reason: reason.into(),
+ },
+ source: None,
+ };
+ if let Some(reason) = &self.unsupported {
+ return unchecked(reason);
+ }
+ if self.near_boundary(t) {
+ return unchecked("on a timeline segment boundary");
+ }
+ let (segment, source_time) = match self.map(t) {
+ Some(Mapping::Single {
+ segment,
+ source_time,
+ }) => (segment, source_time),
+ Some(Mapping::Transition) => return unchecked("clip transition"),
+ None => return unchecked("past the end of the timeline"),
+ };
+ let clip = self.segments[segment].clip;
+ let screen = self.answer(clip, StreamKind::Screen, source_time);
+ let mut camera = if self.camera_hidden {
+ StreamExpectation::Absent
+ } else {
+ self.answer(clip, StreamKind::Camera, source_time)
+ };
+ let mut screen = screen;
+ match self.scene_rule(t) {
+ Some((_, true)) => {
+ camera = StreamExpectation::Unchecked {
+ reason: "scene fade".into(),
+ };
+ }
+ Some((SceneRule::HideCamera, false)) => camera = StreamExpectation::Absent,
+ Some((SceneRule::Unchecked, false)) => {
+ screen = StreamExpectation::Unchecked {
+ reason: "scene layout".into(),
+ };
+ camera = StreamExpectation::Unchecked {
+ reason: "scene layout".into(),
+ };
+ }
+ None => {}
+ }
+ FrameExpectation {
+ screen,
+ camera,
+ source: Some((clip, source_time)),
+ }
+ }
+
+ pub fn expect(&self, output_frame: u32, fps: u32) -> FrameExpectation {
+ self.expect_at(f64::from(output_frame) / f64::from(fps))
+ }
+}
diff --git a/crates/verify/src/report.rs b/crates/verify/src/report.rs
new file mode 100644
index 000000000..820d169a1
--- /dev/null
+++ b/crates/verify/src/report.rs
@@ -0,0 +1,270 @@
+//! Case results, the strict expected-failure list and the JSON report.
+//!
+//! Every case ends in [`finish`]: a failing case listed in
+//! `crates/verify/expectations.txt` passes as XFAIL, a listed case that
+//! passes fails ("remove this xfail"), and any other failure fails with the
+//! exact mismatches and a one-line local repro command.
+
+use std::{io::Write, path::PathBuf, time::Instant};
+
+use serde::{Deserialize, Serialize};
+
+use crate::oracle::StreamReport;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Tier {
+ Fast,
+ Full,
+}
+
+/// `CAP_VERIFY_TIER=full` selects the merge-gate/nightly tier; anything else
+/// (or unset) is the fast PR tier.
+pub fn tier() -> Tier {
+ match std::env::var("CAP_VERIFY_TIER").as_deref() {
+ Ok("full") => Tier::Full,
+ _ => Tier::Fast,
+ }
+}
+
+pub fn platform() -> &'static str {
+ if cfg!(target_os = "macos") {
+ "macos"
+ } else if cfg!(target_os = "windows") {
+ "windows"
+ } else {
+ "linux"
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct CaseResult {
+ pub id: String,
+ pub platform: String,
+ pub tier: Tier,
+ pub passed: bool,
+ pub summary: String,
+ pub streams: Vec<StreamReport>,
+ pub notes: Vec<String>,
+ pub seconds: f64,
+ pub repro: String,
+ pub outcome: String,
+}
+
+pub struct Case {
+ pub id: String,
+ started: Instant,
+ pub streams: Vec<StreamReport>,
+ pub problems: Vec<String>,
+ pub notes: Vec<String>,
+}
+
+impl Case {
+ pub fn new(id: impl Into<String>) -> Self {
+ let id = id.into();
+ eprintln!("[cap-verify] case {id} ({})", platform());
+ Self {
+ id,
+ started: Instant::now(),
+ streams: Vec::new(),
+ problems: Vec::new(),
+ notes: Vec::new(),
+ }
+ }
+
+ pub fn problem(&mut self, text: impl Into<String>) {
+ self.problems.push(text.into());
+ }
+
+ pub fn note(&mut self, text: impl Into<String>) {
+ self.notes.push(text.into());
+ }
+
+ pub fn stream(&mut self, report: StreamReport) {
+ if !report.passed() {
+ self.problems.push(report.summary());
+ }
+ self.streams.push(report);
+ }
+
+ pub fn failed(&self) -> bool {
+ !self.problems.is_empty()
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct Xfail {
+ pub line: usize,
+ pub pattern: String,
+ pub platforms: Vec<String>,
+ pub reason: String,
+}
+
+fn glob_match(pattern: &str, text: &str) -> bool {
+ let parts: Vec<&str> = pattern.split('*').collect();
+ if parts.len() == 1 {
+ return pattern == text;
+ }
+ let mut rest = text;
+ for (i, part) in parts.iter().enumerate() {
+ if i == 0 {
+ let Some(stripped) = rest.strip_prefix(part) else {
+ return false;
+ };
+ rest = stripped;
+ } else if i == parts.len() - 1 {
+ return rest.ends_with(part);
+ } else {
+ let Some(at) = rest.find(part) else {
+ return false;
+ };
+ rest = &rest[at + part.len()..];
+ }
+ }
+ true
+}
+
+pub fn expectations_path() -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("expectations.txt")
+}
+
+/// Parses `expectations.txt`: `<case glob> <platforms|all> <reason...>`.
+pub fn load_expectations() -> Vec<Xfail> {
+ let text = std::fs::read_to_string(expectations_path()).unwrap_or_default();
+ text.lines()
+ .enumerate()
+ .filter_map(|(i, line)| {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ return None;
+ }
+ let mut fields = line.split_whitespace();
+ let pattern = fields.next()?.to_string();
+ let platforms = fields.next()?.split(',').map(str::to_string).collect();
+ let reason = fields.collect::<Vec<_>>().join(" ");
+ Some(Xfail {
+ line: i + 1,
+ pattern,
+ platforms,
+ reason,
+ })
+ })
+ .collect()
+}
+
+pub fn lookup_xfail(id: &str) -> Option<Xfail> {
+ let platform = platform();
+ load_expectations().into_iter().find(|x| {
+ glob_match(&x.pattern, id)
+ && x.platforms
+ .iter()
+ .any(|p| p == "all" || p == platform)
+ })
+}
+
+fn repro_command(id: &str) -> String {
+ let test = id.split('/').next().unwrap_or("export");
+ format!(
+ "CAP_VERIFY_CASE='{id}' CAP_VERIFY_TIER={} cargo test -p cap-verify --test {test} -- --nocapture",
+ match tier() {
+ Tier::Fast => "fast",
+ Tier::Full => "full",
+ }
+ )
+}
+
+/// Whether a case id is selected by `CAP_VERIFY_CASE` (glob, default all).
+pub fn selected(id: &str) -> bool {
+ match std::env::var("CAP_VERIFY_CASE") {
+ Ok(pattern) if !pattern.is_empty() => pattern.split(',').any(|p| glob_match(p, id)),
+ _ => true,
+ }
+}
+
+fn write_result(result: &CaseResult) {
+ let Some(dir) = std::env::var_os("CAP_VERIFY_REPORT_DIR") else {
+ return;
+ };
+ let dir = PathBuf::from(dir);
+ let _ = std::fs::create_dir_all(&dir);
+ let file = dir.join(format!("{}.jsonl", std::process::id()));
+ if let Ok(mut f) = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(file)
+ && let Ok(line) = serde_json::to_string(result)
+ {
+ let _ = writeln!(f, "{line}");
+ }
+}
+
+/// Settles a case against the expectations file. Returns an error message
+/// when the test must fail.
+pub fn settle(case: Case) -> Result<CaseResult, String> {
+ let xfail = lookup_xfail(&case.id);
+ let failed = case.failed();
+ let mut summary = if failed {
+ case.problems.join("\n ")
+ } else {
+ let streams: Vec<String> = case
+ .streams
+ .iter()
+ .map(|s| format!("{} ({} unchecked)", s.summary(), s.unchecked))
+ .collect();
+ format!("all checks passed: {}", streams.join(", "))
+ };
+ let repro = repro_command(&case.id);
+ let outcome = match (&xfail, failed) {
+ (None, false) => "pass",
+ (Some(_), true) => "xfail",
+ (None, true) => "FAIL",
+ (Some(_), false) => "XPASS",
+ };
+ if let Some(x) = &xfail {
+ summary = format!("{summary}\n (expected failure, expectations.txt:{}: {})", x.line, x.reason);
+ }
+ let result = CaseResult {
+ id: case.id.clone(),
+ platform: platform().to_string(),
+ tier: tier(),
+ passed: matches!(outcome, "pass" | "xfail"),
+ summary: summary.clone(),
+ streams: case.streams,
+ notes: case.notes,
+ seconds: case.started.elapsed().as_secs_f64(),
+ repro: repro.clone(),
+ outcome: outcome.to_string(),
+ };
+ write_result(&result);
+ eprintln!(
+ "[cap-verify] {outcome} {} in {:.1}s\n {summary}",
+ result.id, result.seconds
+ );
+ match outcome {
+ "FAIL" => Err(format!(
+ "case {} failed:\n {summary}\n repro: {repro}",
+ result.id
+ )),
+ "XPASS" => Err(format!(
+ "case {} now passes: remove its xfail ({}:{})\n repro: {repro}",
+ result.id,
+ expectations_path().display(),
+ xfail.map_or(0, |x| x.line)
+ )),
+ _ => Ok(result),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::glob_match;
+
+ #[test]
+ fn globs() {
+ assert!(glob_match("export/*", "export/basic/mp4"));
+ assert!(glob_match("export/*/avf", "export/jitter/avf"));
+ assert!(!glob_match("export/*/avf", "export/jitter/ffmpeg"));
+ assert!(glob_match("a", "a"));
+ assert!(!glob_match("a", "ab"));
+ }
+}
diff --git a/crates/verify/tests/common/mod.rs b/crates/verify/tests/common/mod.rs
new file mode 100644
index 000000000..d53a974fd
--- /dev/null
+++ b/crates/verify/tests/common/mod.rs
@@ -0,0 +1,252 @@
+#![allow(dead_code)]
+
+use std::path::{Path, PathBuf};
+
+use cap_project::{
+ ClipTransition, ClipTransitionType, ProjectConfiguration, RecordingMeta, TimelineSegment, XY,
+};
+use cap_verify::{
+ fixture::{self, FixtureSpec, SourceTruth},
+ media,
+ model::ReferenceModel,
+ oracle::{self, StreamExpectation},
+ report::{self, Case},
+ video_code::{self, FrameReadout, StreamKind},
+};
+
+pub fn runtime() -> tokio::runtime::Runtime {
+ tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(4)
+ .thread_stack_size(16 * 1024 * 1024)
+ .enable_all()
+ .build()
+ .expect("runtime")
+}
+
+pub fn init() {
+ media::init();
+}
+
+/// A ready fixture project plus its decoded source truth.
+pub struct Project {
+ pub path: PathBuf,
+ pub meta: RecordingMeta,
+ pub truth: SourceTruth,
+}
+
+pub fn project(spec: &FixtureSpec) -> Project {
+ init();
+ let path = fixture::ensure_fixture(spec, fixture::write_fixture)
+ .unwrap_or_else(|e| panic!("fixture {}: {e:?}", spec.name));
+ let meta = RecordingMeta::load_for_project(&path).expect("fixture meta");
+ let truth = SourceTruth::read(&path).expect("fixture truth");
+ Project { path, meta, truth }
+}
+
+impl Project {
+ pub fn config(&self) -> ProjectConfiguration {
+ self.meta.project_config()
+ }
+
+ pub fn model(&self, config: &ProjectConfiguration) -> ReferenceModel {
+ ReferenceModel::new(&self.meta, config, self.truth.clone()).expect("model")
+ }
+}
+
+/// Replaces the timeline with `(start, end, timescale)` cuts of clip 0.
+pub fn set_cuts(config: &mut ProjectConfiguration, cuts: &[(f64, f64, f64)]) {
+ let timeline = config.timeline.as_mut().expect("timeline");
+ timeline.segments = cuts
+ .iter()
+ .map(|&(start, end, timescale)| TimelineSegment {
+ recording_clip: 0,
+ start,
+ end,
+ timescale,
+ name: None,
+ speed_audio_mode: None,
+ hide_cursor: None,
+ volume: None,
+ })
+ .collect();
+}
+
+pub fn add_transition(config: &mut ProjectConfiguration, segment_index: u32, duration: f64) {
+ let timeline = config.timeline.as_mut().expect("timeline");
+ timeline.transitions.push(ClipTransition {
+ segment_index,
+ kind: ClipTransitionType::CrossFade,
+ duration,
+ });
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Format {
+ Mp4,
+ Gif,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Decoder {
+ /// The platform default (AVAssetReader on macOS, FFmpeg elsewhere).
+ Default,
+ /// `--force-ffmpeg-decoder`.
+ Ffmpeg,
+}
+
+impl Decoder {
+ pub fn label(self) -> &'static str {
+ match self {
+ Decoder::Default if cfg!(target_os = "macos") => "avf",
+ Decoder::Default => "ffmpeg",
+ Decoder::Ffmpeg => "ffmpeg",
+ }
+ }
+
+ /// Decoders that are actually distinct on this platform.
+ pub fn all() -> Vec<Decoder> {
+ if cfg!(target_os = "macos") {
+ vec![Decoder::Default, Decoder::Ffmpeg]
+ } else {
+ vec![Decoder::Default]
+ }
+ }
+}
+
+pub struct ExportRun {
+ pub fps: u32,
+ pub resolution: (u32, u32),
+ pub format: Format,
+ pub decoder: Decoder,
+}
+
+pub async fn export(
+ project: &Project,
+ config: ProjectConfiguration,
+ run: &ExportRun,
+ out: &Path,
+) -> Result<PathBuf, String> {
+ let force = run.decoder == Decoder::Ffmpeg;
+ let base = cap_export::ExporterBase::builder(project.path.clone())
+ .with_config(config)
+ .with_force_ffmpeg_decoder(force)
+ .with_output_path(out.to_path_buf())
+ .build()
+ .await
+ .map_err(|e| format!("exporter build: {e}"))?;
+ let resolution_base = XY::new(run.resolution.0, run.resolution.1);
+ match run.format {
+ Format::Mp4 => {
+ cap_export::mp4::Mp4ExportSettings {
+ fps: run.fps,
+ resolution_base,
+ compression: cap_export::mp4::ExportCompression::Social,
+ custom_bpp: None,
+ force_ffmpeg_decoder: force,
+ optimize_filesize: false,
+ }
+ .export(base, |_| true)
+ .await
+ }
+ Format::Gif => {
+ cap_export::gif::GifExportSettings {
+ fps: run.fps,
+ resolution_base,
+ quality: None,
+ }
+ .export(base, |_| true)
+ .await
+ }
+ }
+}
+
+pub struct OutputFrame {
+ pub pts_secs: f64,
+ pub readout: FrameReadout,
+ /// Hash of the decoded picture, for determinism checks.
+ pub hash: u64,
+}
+
+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 { 2 } else { 3 };
+ for plane in 0..planes.min(frame.planes()) {
+ let width = frame.plane_width(plane) as usize
+ * if frame.format() == ffmpeg::format::Pixel::NV12 && plane == 1 { 2 } else { 1 };
+ let stride = frame.stride(plane);
+ let data = frame.data(plane);
+ for row in 0..frame.plane_height(plane) as usize {
+ for &byte in &data[row * stride..row * stride + width] {
+ hash ^= u64::from(byte);
+ hash = hash.wrapping_mul(0x0100_0000_01b3);
+ }
+ }
+ }
+ hash
+}
+
+pub fn read_output(path: &Path) -> Vec<OutputFrame> {
+ let mut frames = Vec::new();
+ media::decode_video(path, |picture| {
+ frames.push(OutputFrame {
+ pts_secs: picture.pts_secs,
+ readout: video_code::read_frame(&picture.view()),
+ hash: picture_hash(&picture.frame),
+ })
+ })
+ .unwrap_or_else(|e| panic!("decode {path:?}: {e:?}"));
+ frames
+}
+
+/// Checks a sequential output (export or sequential playback) frame by frame
+/// against the model.
+pub fn check_sequence(
+ case: &mut Case,
+ model: &ReferenceModel,
+ frames: &[OutputFrame],
+ fps: u32,
+ check_timestamps: bool,
+) {
+ let expected_count = model.output_frames(fps);
+ if frames.len() as u32 != expected_count {
+ case.problem(format!(
+ "output has {} frames, the model expects {expected_count} ({:.3}s at {fps} fps)",
+ frames.len(),
+ model.duration()
+ ));
+ }
+ if check_timestamps {
+ let off_grid: Vec<(usize, f64)> = frames
+ .iter()
+ .enumerate()
+ .filter(|(i, f)| (f.pts_secs - *i as f64 / f64::from(fps)).abs() > 0.5 / f64::from(fps))
+ .map(|(i, f)| (i, f.pts_secs))
+ .take(5)
+ .collect();
+ if !off_grid.is_empty() {
+ case.problem(format!("output timestamps off the {fps} fps grid: {off_grid:?}"));
+ }
+ }
+ let n = frames.len().min(expected_count as usize);
+ let expectations: Vec<_> = (0..n as u32).map(|i| model.expect(i, fps)).collect();
+ for kind in StreamKind::ALL {
+ let exp: Vec<StreamExpectation> = expectations.iter().map(|e| e.get(kind).clone()).collect();
+ let obs: Vec<_> = frames[..n].iter().map(|f| f.readout.get(kind).clone()).collect();
+ case.stream(oracle::check_stream(kind, &exp, &obs, fps));
+ }
+}
+
+pub fn finish(case: Case) {
+ if let Err(message) = report::settle(case) {
+ panic!("{message}");
+ }
+}
+
+pub fn scratch_dir(name: &str) -> tempfile::TempDir {
+ let root = fixture::fixture_root().join("scratch");
+ std::fs::create_dir_all(&root).expect("scratch root");
+ tempfile::Builder::new()
+ .prefix(&format!("{}-", name.replace('/', "_")))
+ .tempdir_in(root)
+ .expect("scratch dir")
+}
diff --git a/crates/verify/tests/export.rs b/crates/verify/tests/export.rs
new file mode 100644
index 000000000..384a08af8
--- /dev/null
+++ b/crates/verify/tests/export.rs
@@ -0,0 +1,276 @@
+//! Export oracle: every exported frame must show exactly the source frames
+//! the reference model computes, for both streams, on every decoder.
+
+mod common;
+
+use cap_project::{ProjectConfiguration, SceneMode, SceneSegment};
+use cap_verify::{
+ catalog,
+ fixture::FixtureSpec,
+ report::{self, Case, Tier},
+};
+use common::{Decoder, ExportRun, Format};
+
+struct Variant {
+ edit: &'static str,
+ apply: fn(&mut ProjectConfiguration),
+}
+
+fn no_edit(_: &mut ProjectConfiguration) {}
+
+fn case_id(fixture: &str, edit: &str, format: Format, fps: u32, decoder: Decoder) -> String {
+ let format = match format {
+ Format::Mp4 => "mp4",
+ Format::Gif => "gif",
+ };
+ format!("export/{fixture}/{edit}/{format}{fps}/{}", decoder.label())
+}
+
+/// Exports `spec` with each edit, format, rate and decoder and checks every
+/// frame. With `determinism`, the first combination is exported twice and
+/// the decoded pictures must be identical.
+fn run(
+ spec: FixtureSpec,
+ variants: &[Variant],
+ formats: &[(Format, u32)],
+ decoders: &[Decoder],
+ resolution: (u32, u32),
+ determinism: bool,
+) {
+ let project = common::project(&spec);
+ let rt = common::runtime();
+ let mut failures = Vec::new();
+ for variant in variants {
+ for &(format, fps) in formats {
+ for &decoder in decoders {
+ let id = case_id(&spec.name, variant.edit, format, fps, decoder);
+ if !report::selected(&id) {
+ continue;
+ }
+ let mut config = project.config();
+ (variant.apply)(&mut config);
+ let model = project.model(&config);
+ let mut case = Case::new(&id);
+ let dir = common::scratch_dir(&id);
+ let ext = if format == Format::Gif { "gif" } else { "mp4" };
+ let run = ExportRun {
+ fps,
+ resolution,
+ format,
+ decoder,
+ };
+ let first = dir.path().join(format!("a.{ext}"));
+ match rt.block_on(common::export(&project, config.clone(), &run, &first)) {
+ Err(e) => case.problem(format!("export failed: {e}")),
+ Ok(path) => {
+ let frames = common::read_output(&path);
+ common::check_sequence(&mut case, &model, &frames, fps, format == Format::Mp4);
+ if determinism {
+ let second = dir.path().join(format!("b.{ext}"));
+ match rt.block_on(common::export(&project, config, &run, &second)) {
+ Err(e) => case.problem(format!("second export failed: {e}")),
+ Ok(path) => {
+ let again = common::read_output(&path);
+ let differing: Vec<usize> = frames
+ .iter()
+ .zip(&again)
+ .enumerate()
+ .filter(|(_, (a, b))| a.hash != b.hash)
+ .map(|(i, _)| i)
+ .collect();
+ if !differing.is_empty() || frames.len() != again.len() {
+ case.problem(format!(
+ "nondeterministic: {} of {} frames differ between two exports (first {:?})",
+ differing.len(),
+ frames.len(),
+ &differing[..differing.len().min(5)]
+ ));
+ }
+ }
+ }
+ }
+ }
+ }
+ if let Err(message) = report::settle(case) {
+ failures.push(message);
+ }
+ }
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+const RES: (u32, u32) = (480, 270);
+
+fn cuts_speeds_reorder(config: &mut ProjectConfiguration) {
+ common::set_cuts(
+ config,
+ &[
+ (0.5, 2.0, 1.0),
+ (2.5, 4.0, 2.0),
+ (1.0, 2.0, 0.5),
+ (4.0, 5.8, 1.5),
+ ],
+ );
+}
+
+fn transition(config: &mut ProjectConfiguration) {
+ common::set_cuts(config, &[(0.0, 2.5, 1.0), (3.5, 6.0, 1.0)]);
+ common::add_transition(config, 1, 0.4);
+}
+
+fn camera_hidden(config: &mut ProjectConfiguration) {
+ config.camera.hide = true;
+}
+
+fn hide_camera_scene(config: &mut ProjectConfiguration) {
+ config
+ .timeline
+ .as_mut()
+ .expect("timeline")
+ .scene_segments
+ .push(SceneSegment {
+ start: 2.0,
+ end: 4.0,
+ mode: SceneMode::HideCamera,
+ split_layout: None,
+ transition_in: 0.3,
+ transition_out: 0.3,
+ });
+}
+
+#[test]
+fn basic() {
+ run(
+ catalog::basic(report::tier()),
+ &[
+ Variant {
+ edit: "full",
+ apply: no_edit,
+ },
+ Variant {
+ edit: "cuts-speeds-reorder",
+ apply: cuts_speeds_reorder,
+ },
+ Variant {
+ edit: "transition",
+ apply: transition,
+ },
+ Variant {
+ edit: "camera-hidden",
+ apply: camera_hidden,
+ },
+ Variant {
+ edit: "hide-camera-scene",
+ apply: hide_camera_scene,
+ },
+ ],
+ &[(Format::Mp4, 30), (Format::Mp4, 60)],
+ &Decoder::all(),
+ RES,
+ false,
+ );
+}
+
+#[test]
+fn gif() {
+ run(
+ catalog::basic(report::tier()),
+ &[Variant {
+ edit: "cuts-speeds-reorder",
+ apply: cuts_speeds_reorder,
+ }],
+ &[(Format::Gif, 15)],
+ &[Decoder::Default],
+ (320, 180),
+ false,
+ );
+}
+
+#[test]
+fn vfr_holds() {
+ run(
+ catalog::vfr_holds(report::tier()),
+ &[Variant {
+ edit: "full",
+ apply: no_edit,
+ }],
+ &[(Format::Mp4, 30), (Format::Mp4, 60)],
+ &Decoder::all(),
+ RES,
+ false,
+ );
+}
+
+/// Long recordings with a jittery ~12 fps camera at 30 fps nominal exported
+/// at 60 fps: the camera must never run ahead of the screen.
+#[test]
+fn jitter_camera() {
+ run(
+ catalog::jitter_camera(report::tier()),
+ &[Variant {
+ edit: "full",
+ apply: no_edit,
+ }],
+ &[(Format::Mp4, 60)],
+ &Decoder::all(),
+ RES,
+ report::tier() == Tier::Full,
+ );
+}
+
+fn backward_jumps(config: &mut ProjectConfiguration) {
+ common::set_cuts(config, &[(5.0, 35.0, 1.0), (44.0, 50.0, 1.0), (28.0, 45.0, 1.0)]);
+}
+
+/// Play past a long hold, elsewhere, then jump back into the hold.
+#[test]
+fn backward_hold() {
+ run(
+ catalog::backward_hold(report::tier()),
+ &[Variant {
+ edit: "backward-jumps",
+ apply: backward_jumps,
+ }],
+ &[(Format::Mp4, 30), (Format::Mp4, 60)],
+ &Decoder::all(),
+ RES,
+ false,
+ );
+}
+
+#[test]
+fn start_offsets() {
+ for spec in [
+ catalog::late_camera(report::tier()),
+ catalog::early_camera(report::tier()),
+ catalog::camera_pts_late(report::tier()),
+ ] {
+ run(
+ spec,
+ &[Variant {
+ edit: "full",
+ apply: no_edit,
+ }],
+ &[(Format::Mp4, 30)],
+ &Decoder::all(),
+ RES,
+ false,
+ );
+ }
+}
+
+#[test]
+fn multi_segment() {
+ run(
+ catalog::multi_segment(report::tier()),
+ &[Variant {
+ edit: "full",
+ apply: no_edit,
+ }],
+ &[(Format::Mp4, 30)],
+ &Decoder::all(),
+ RES,
+ true,
+ );
+}