Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(verify): offline playback and seek oracle tests

Richie McIlroy4a41a09a7f83
diff --git a/crates/verify/src/media.rs b/crates/verify/src/media.rs
index 82022ed7e..0a397881d 100644
--- a/crates/verify/src/media.rs
+++ b/crates/verify/src/media.rs
@@ -372,6 +372,26 @@ pub fn video_packet_times(path: &Path) -> anyhow::Result<Vec<f64>> {
Ok(times)
}
+/// Presentation times of the keyframes of the best video stream, sorted.
+pub fn keyframe_times(path: &Path) -> anyhow::Result<Vec<f64>> {
+ init();
+ let mut input = format::input(&path).with_context(|| format!("open {path:?}"))?;
+ let stream = input
+ .streams()
+ .best(Type::Video)
+ .ok_or_else(|| anyhow!("{path:?} has no video stream"))?;
+ let index = stream.index();
+ let tb = stream.time_base();
+ let mut times: Vec<f64> = input
+ .packets()
+ .filter(|(s, p)| s.index() == index && p.is_key())
+ .filter_map(|(_, p)| p.pts())
+ .map(|pts| pts as f64 * f64::from(tb.numerator()) / f64::from(tb.denominator()))
+ .collect();
+ times.sort_by(f64::total_cmp);
+ Ok(times)
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioCodec {
Aac,
diff --git a/crates/verify/src/oracle.rs b/crates/verify/src/oracle.rs
index 93b0e5d9e..a94c9a847 100644
--- a/crates/verify/src/oracle.rs
+++ b/crates/verify/src/oracle.rs
@@ -57,6 +57,8 @@ pub enum MismatchKind {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Mismatch {
+ /// Position in the checked sequence (request number for seek runs).
+ pub position: usize,
pub output_frame: u32,
pub time_secs: f64,
pub kind: MismatchKind,
@@ -133,10 +135,23 @@ impl StreamReport {
text.push_str(&format!(", up to {} stale", self.max_stale));
}
if let Some(first) = self.mismatches.first() {
- text.push_str(&format!(
- "; first at output frame {} ({:.3}s): expected {:?}, got {:?}",
- first.output_frame, first.time_secs, first.expected, first.observed
- ));
+ let shown: Vec<String> = self
+ .mismatches
+ .iter()
+ .take(4)
+ .map(|m| {
+ 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("; ")));
+ let _ = first;
}
text
}
@@ -167,7 +182,12 @@ pub fn check_stream_at(
};
let mut expected_counts: BTreeMap<(u8, u32), u32> = BTreeMap::new();
let mut observed_counts: BTreeMap<(u8, u32), u32> = BTreeMap::new();
- for ((expectation, readout), &frame) in expectations.iter().zip(observed).zip(frame_numbers) {
+ for (position, ((expectation, readout), &frame)) in expectations
+ .iter()
+ .zip(observed)
+ .zip(frame_numbers)
+ .enumerate()
+ {
let time_secs = f64::from(frame) / f64::from(fps);
let push = |report: &mut StreamReport,
kind: MismatchKind,
@@ -175,6 +195,7 @@ pub fn check_stream_at(
delta: Option<i64>,
detail: Option<String>| {
report.mismatches.push(Mismatch {
+ position,
output_frame: frame,
time_secs,
kind,
diff --git a/crates/verify/tests/common/mod.rs b/crates/verify/tests/common/mod.rs
index d53a974fd..a99ceeafe 100644
--- a/crates/verify/tests/common/mod.rs
+++ b/crates/verify/tests/common/mod.rs
@@ -250,3 +250,170 @@ pub fn scratch_dir(name: &str) -> tempfile::TempDir {
.tempdir_in(root)
.expect("scratch dir")
}
+
+/// Drives the editor's decode + render path offline, one requested frame
+/// at a time (no wall clock): `create_segments` decoders, `FrameRenderer`,
+/// `RendererLayers`. Seeks use `get_frames_initial` like the preview
+/// renderer; frames that follow a seek use `get_frames` like playback.
+pub struct Player {
+ constants: std::sync::Arc<cap_rendering::RenderVideoConstants>,
+ segments: Vec<cap_editor::SegmentMedia>,
+ renderer: Option<cap_rendering::FrameRenderer<'static>>,
+ layers: cap_rendering::RendererLayers,
+ zooms: Vec<cap_rendering::ZoomTransformTimeline>,
+ config: ProjectConfiguration,
+ duration: f64,
+ resolution: XY<u32>,
+}
+
+impl Player {
+ pub async fn open(
+ project: &Project,
+ config: ProjectConfiguration,
+ decoder: Decoder,
+ resolution: (u32, u32),
+ ) -> Result<Self, String> {
+ let meta = project.meta.studio_meta().ok_or("not studio")?.clone();
+ let recordings = cap_rendering::ProjectRecordingsMeta::new(&project.path, &meta)?;
+ let constants = std::sync::Arc::new(
+ cap_rendering::RenderVideoConstants::new(
+ &recordings.segments,
+ project.meta.clone(),
+ meta.clone(),
+ )
+ .await
+ .map_err(|e| format!("render constants: {e}"))?,
+ );
+ let segments =
+ cap_editor::create_segments(&project.meta, &meta, decoder == Decoder::Ffmpeg).await?;
+ let mut layers = cap_rendering::RendererLayers::new_with_options(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ );
+ let (sw, sh) = segments[0].decoders.screen_video_dimensions();
+ let camera = segments[0].decoders.camera_video_dimensions();
+ layers.prepare_for_video_dimensions(
+ &constants.device,
+ sw,
+ sh,
+ camera.map(|c| c.0),
+ camera.map(|c| c.1),
+ );
+ let duration = config.timeline.as_ref().map_or(0.0, |t| t.duration());
+ let zooms = segments
+ .iter()
+ .map(|s| {
+ cap_rendering::ZoomTransformTimeline::from_project(
+ &config,
+ &s.cursor,
+ duration,
+ constants.options.screen_size,
+ )
+ })
+ .collect();
+ // The renderer borrows the constants; both live as long as the
+ // player, and the Arc keeps the constants' address stable.
+ let constants_ref: &'static cap_rendering::RenderVideoConstants =
+ unsafe { &*std::sync::Arc::as_ptr(&constants) };
+ Ok(Self {
+ renderer: Some(cap_rendering::FrameRenderer::new(constants_ref)),
+ constants,
+ segments,
+ layers,
+ zooms,
+ config,
+ duration,
+ resolution: XY::new(resolution.0, resolution.1),
+ })
+ }
+
+ pub fn prefer_sequential(&self) {
+ for segment in &self.segments {
+ segment.decoders.prefer_sequential_access();
+ }
+ }
+
+ /// Renders output frame `frame` and reads its markers. `None` when the
+ /// timeline has no segment there or the decoders returned nothing.
+ pub async fn frame(&mut self, frame: u32, fps: u32, seek: bool) -> Result<FrameReadout, String> {
+ let t = f64::from(frame) / f64::from(fps);
+ let (segment_time, segment) = self
+ .config
+ .get_segment_time(t)
+ .ok_or_else(|| format!("no timeline segment at {t:.3}s"))?;
+ let clip = segment.recording_clip;
+ let media = &self.segments[clip as usize];
+ let offsets = self
+ .config
+ .clips
+ .iter()
+ .find(|c| c.index == clip)
+ .map(|c| c.offsets)
+ .unwrap_or_default();
+ let needs_camera = !self.config.camera.hide;
+ let frames = if seek {
+ media
+ .decoders
+ .get_frames_initial(segment_time as f32, needs_camera, true, offsets)
+ .await
+ } else {
+ media
+ .decoders
+ .get_frames(segment_time as f32, needs_camera, true, offsets)
+ .await
+ }
+ .ok_or_else(|| format!("decoders returned no frame at {t:.3}s"))?;
+ let zoom = &mut self.zooms[clip as usize];
+ zoom.ensure_precomputed_until((frame as f32 + 1.0) / fps as f32);
+ let uniforms = cap_rendering::ProjectUniforms::new(
+ &self.constants,
+ &self.config,
+ frame,
+ fps,
+ self.resolution,
+ &media.cursor,
+ &frames,
+ self.duration,
+ zoom,
+ );
+ let rendered = self
+ .renderer
+ .as_mut()
+ .expect("renderer")
+ .render_immediate(frames, uniforms, &media.cursor, true, &mut self.layers)
+ .await
+ .map_err(|e| format!("render: {e}"))?;
+ let view = video_code::PackedFrame {
+ data: &rendered.data,
+ width: rendered.width as usize,
+ height: rendered.height as usize,
+ stride: rendered.padded_bytes_per_row as usize,
+ order: video_code::PixelOrder::Rgba,
+ };
+ Ok(video_code::read_frame(&view))
+ }
+}
+
+impl Drop for Player {
+ fn drop(&mut self) {
+ // Drop the renderer before the constants it borrows.
+ self.renderer.take();
+ }
+}
+
+/// Checks a list of (output frame, readout) pairs against the model.
+pub fn check_requests(
+ case: &mut Case,
+ model: &ReferenceModel,
+ frames: &[u32],
+ readouts: &[FrameReadout],
+ fps: u32,
+) {
+ let expectations: Vec<_> = frames.iter().map(|&f| model.expect(f, fps)).collect();
+ for kind in StreamKind::ALL {
+ let exp: Vec<StreamExpectation> = expectations.iter().map(|e| e.get(kind).clone()).collect();
+ let obs: Vec<_> = readouts.iter().map(|r| r.get(kind).clone()).collect();
+ case.stream(oracle::check_stream_at(kind, &exp, &obs, frames, fps));
+ }
+}
diff --git a/crates/verify/tests/playback.rs b/crates/verify/tests/playback.rs
new file mode 100644
index 000000000..c6e73759d
--- /dev/null
+++ b/crates/verify/tests/playback.rs
@@ -0,0 +1,115 @@
+//! Playback oracle: the editor's decode + render path, driven offline frame
+//! by frame, must show exactly the frames the model (and therefore the
+//! export) shows: from the start, from the middle, through holds, across
+//! cuts and backward timeline jumps.
+
+mod common;
+
+use cap_project::ProjectConfiguration;
+use cap_verify::{
+ catalog,
+ fixture::{FixtureSpec, Rng},
+ report::{self, Case, Tier},
+};
+use common::Decoder;
+
+const RES: (u32, u32) = (480, 270);
+
+fn no_edit(_: &mut ProjectConfiguration) {}
+
+fn cuts(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 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)]);
+}
+
+/// Plays `[start, end)` output frames sequentially (the first as a seek).
+fn sequential(
+ spec: FixtureSpec,
+ edit: (&str, fn(&mut ProjectConfiguration)),
+ fps: u32,
+ start_fraction: f64,
+) {
+ let project = common::project(&spec);
+ let rt = common::runtime();
+ let mut failures = Vec::new();
+ for decoder in Decoder::all() {
+ let id = format!(
+ "playback/{}/{}/seq{fps}-from{:.0}/{}",
+ spec.name,
+ edit.0,
+ start_fraction * 100.0,
+ decoder.label()
+ );
+ if !report::selected(&id) {
+ continue;
+ }
+ let mut config = project.config();
+ (edit.1)(&mut config);
+ let model = project.model(&config);
+ let total = model.output_frames(fps);
+ let first = (f64::from(total) * start_fraction) as u32;
+ let mut case = Case::new(&id);
+ let frames: Vec<u32> = (first..total).collect();
+ let result = rt.block_on(async {
+ let mut player = common::Player::open(&project, config, decoder, RES).await?;
+ let mut readouts = Vec::new();
+ for &f in &frames {
+ readouts.push(player.frame(f, fps, f == first).await?);
+ }
+ Ok::<_, String>(readouts)
+ });
+ match result {
+ Ok(readouts) => common::check_requests(&mut case, &model, &frames, &readouts, fps),
+ Err(e) => case.problem(e),
+ }
+ if let Err(message) = report::settle(case) {
+ failures.push(message);
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+#[test]
+fn basic_sequential() {
+ sequential(catalog::basic(report::tier()), ("full", no_edit), 30, 0.0);
+ sequential(catalog::basic(report::tier()), ("cuts-speeds-reorder", cuts), 60, 0.0);
+}
+
+#[test]
+fn play_from_middle() {
+ let seed = 0x9A1D_0001;
+ let mut rng = Rng::new(seed);
+ eprintln!("seed {seed:#x}");
+ for _ in 0..2 {
+ let start = 0.2 + rng.f64() * 0.6;
+ sequential(catalog::basic(report::tier()), ("full", no_edit), 30, start);
+ }
+ sequential(catalog::vfr_holds(report::tier()), ("full", no_edit), 60, 0.3);
+}
+
+#[test]
+fn vfr_holds_sequential() {
+ sequential(catalog::vfr_holds(report::tier()), ("full", no_edit), 30, 0.0);
+}
+
+#[test]
+fn backward_jumps_sequential() {
+ sequential(catalog::backward_hold(report::tier()), ("backward-jumps", backward_jumps), 30, 0.0);
+}
+
+#[test]
+fn jitter_camera_sequential() {
+ let fps = if report::tier() == Tier::Full { 60 } else { 30 };
+ sequential(catalog::jitter_camera(report::tier()), ("full", no_edit), fps, 0.0);
+}
+
+#[test]
+fn multi_segment_sequential() {
+ sequential(catalog::multi_segment(report::tier()), ("full", no_edit), 30, 0.0);
+}
diff --git a/crates/verify/tests/seek.rs b/crates/verify/tests/seek.rs
new file mode 100644
index 000000000..7be9c756b
--- /dev/null
+++ b/crates/verify/tests/seek.rs
@@ -0,0 +1,192 @@
+//! Seek oracle: random seek storms, keyframe-exact seeks, scrubbing in both
+//! directions, seeks into holds and cold opens, all checked against the
+//! model. Seeds are fixed and printed; the full tier runs many more seeks.
+
+mod common;
+
+use cap_project::ProjectConfiguration;
+use cap_verify::{
+ catalog,
+ fixture::{FixtureSpec, Rng},
+ media,
+ report::{self, Case, Tier},
+};
+use common::{Decoder, Player};
+
+const RES: (u32, u32) = (480, 270);
+
+/// One request: output frame and whether it is a seek (vs a follow-on
+/// playback frame).
+type Request = (u32, bool);
+
+fn run(
+ spec: FixtureSpec,
+ name: &str,
+ fps: u32,
+ edit: fn(&mut ProjectConfiguration),
+ make: &dyn Fn(u32, &common::Project) -> Vec<Request>,
+) {
+ let project = common::project(&spec);
+ let rt = common::runtime();
+ let mut failures = Vec::new();
+ for decoder in Decoder::all() {
+ let id = format!("seek/{}/{name}{fps}/{}", spec.name, decoder.label());
+ if !report::selected(&id) {
+ continue;
+ }
+ let mut config = project.config();
+ edit(&mut config);
+ let model = project.model(&config);
+ let requests = make(model.output_frames(fps), &project);
+ let mut case = Case::new(&id);
+ case.note(format!("{} requests", requests.len()));
+ let result = rt.block_on(async {
+ let mut player = Player::open(&project, config, decoder, RES).await?;
+ let mut readouts = Vec::new();
+ for &(frame, seek) in &requests {
+ readouts.push(player.frame(frame, fps, seek).await?);
+ }
+ Ok::<_, String>(readouts)
+ });
+ let frames: Vec<u32> = requests.iter().map(|r| r.0).collect();
+ match result {
+ Ok(readouts) => common::check_requests(&mut case, &model, &frames, &readouts, fps),
+ Err(e) => case.problem(e),
+ }
+ if let Err(message) = report::settle(case) {
+ failures.push(message);
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
+fn no_edit(_: &mut ProjectConfiguration) {}
+
+fn seek_count(fast: usize, full: usize) -> usize {
+ match report::tier() {
+ Tier::Fast => fast,
+ Tier::Full => full,
+ }
+}
+
+/// Random seeks, each followed by 0..=3 playback frames.
+fn storm(seed: u64, count: usize) -> impl Fn(u32, &common::Project) -> Vec<Request> {
+ move |total, _| {
+ eprintln!("seek storm seed {seed:#x}, {count} seeks");
+ let mut rng = Rng::new(seed);
+ let mut out = Vec::new();
+ for _ in 0..count {
+ let frame = rng.range(0, u64::from(total - 4)) as u32;
+ out.push((frame, true));
+ for k in 1..=rng.range(0, 3) as u32 {
+ out.push((frame + k, false));
+ }
+ }
+ out
+ }
+}
+
+#[test]
+fn random_storm() {
+ let count = seek_count(150, 3000);
+ run(catalog::seek_gop(report::tier()), "storm", 30, no_edit, &storm(0x5EE4_0001, count));
+ run(catalog::vfr_holds(report::tier()), "storm", 60, no_edit, &storm(0x5EE4_0002, count));
+}
+
+/// Seeks landing exactly on every source keyframe (and the frame before
+/// it), in shuffled order: a reader started a hair before the keyframe
+/// decodes the previous GOP and shows its last frame.
+#[test]
+fn keyframe_seeks() {
+ let keyframes = |total: u32, project: &common::Project| {
+ let display = project.path.join("content/segments/segment-0/display.mp4");
+ let times = media::keyframe_times(&display).expect("keyframes");
+ let mut frames: Vec<u32> = times
+ .iter()
+ .flat_map(|t| {
+ let f = (t * 30.0).round() as u32;
+ [f, f.saturating_sub(1), f + 1]
+ })
+ .filter(|&f| f < total)
+ .collect();
+ let mut rng = Rng::new(0x5EE4_0003);
+ for i in (1..frames.len()).rev() {
+ let j = rng.range(0, i as u64) as usize;
+ frames.swap(i, j);
+ }
+ frames.into_iter().map(|f| (f, true)).collect()
+ };
+ run(catalog::seek_gop(report::tier()), "keyframes", 30, no_edit, &keyframes);
+}
+
+/// Scrubbing: seek every 0.25 s forwards, then backwards.
+#[test]
+fn scrub() {
+ let scrub = |total: u32, _: &common::Project| {
+ let step = 7;
+ let mut out: Vec<Request> = (0..total).step_by(step).map(|f| (f, true)).collect();
+ out.extend((0..total).rev().step_by(step).map(|f| (f, true)));
+ out
+ };
+ run(catalog::seek_gop(report::tier()), "scrub", 30, no_edit, &scrub);
+ run(catalog::vfr_holds(report::tier()), "scrub", 60, no_edit, &scrub);
+}
+
+/// Seeks into the middle of static holds and across them, then playback
+/// out of the hold.
+#[test]
+fn seek_into_holds() {
+ let into_holds = |total: u32, _: &common::Project| {
+ let mut out = Vec::new();
+ for t in [2.0, 3.5, 1.2, 9.0, 11.1, 5.2, 7.05, 2.3] {
+ let f = (t * 60.0) as u32;
+ if f + 30 < total {
+ out.push((f, true));
+ out.extend((1..30).map(|k| (f + k, false)));
+ }
+ }
+ out
+ };
+ run(catalog::vfr_holds(report::tier()), "into-holds", 60, no_edit, &into_holds);
+}
+
+/// The first frame after opening a project, at several positions.
+#[test]
+fn cold_open() {
+ let spec = catalog::seek_gop(report::tier());
+ let project = common::project(&spec);
+ let rt = common::runtime();
+ let mut failures = Vec::new();
+ for decoder in Decoder::all() {
+ let id = format!("seek/{}/cold-open30/{}", spec.name, decoder.label());
+ if !report::selected(&id) {
+ continue;
+ }
+ let config = project.config();
+ let model = project.model(&config);
+ let total = model.output_frames(30);
+ let frames: Vec<u32> = [0.0, 0.37, 0.71, 0.93]
+ .iter()
+ .map(|p| (f64::from(total - 1) * p) as u32)
+ .collect();
+ let mut case = Case::new(&id);
+ let mut readouts = Vec::new();
+ for &frame in &frames {
+ let result = rt.block_on(async {
+ let mut player = Player::open(&project, config.clone(), decoder, RES).await?;
+ player.frame(frame, 30, true).await
+ });
+ match result {
+ Ok(readout) => readouts.push(readout),
+ Err(e) => case.problem(e),
+ }
+ }
+ if readouts.len() == frames.len() {
+ common::check_requests(&mut case, &model, &frames, &readouts, 30);
+ }
+ if let Err(message) = report::settle(case) {
+ failures.push(message);
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}