Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(verify): captions and editing oracles with random edit sequences

Richie McIlroyf16b472a92d8
diff --git a/crates/verify/tests/captions.rs b/crates/verify/tests/captions.rs
new file mode 100644
index 000000000..652ed5cc1
--- /dev/null
+++ b/crates/verify/tests/captions.rs
@@ -0,0 +1,1699 @@
+//! Captions oracle, with no transcription model anywhere:
+//!
+//! - `projection_*`: random source-timed captions (gaps, punctuation, words
+//! stretched across silences, text-only captions, style overrides) through
+//! random edit sequences (`edits.rs`) must project onto the output timeline
+//! exactly as the reference model below says (`derive_caption_track_segments`
+//! via `synchronize_captions`, the call the editor, export and render farm
+//! make).
+//! - `legacy_migration`: output-timed captions from older projects are moved
+//! to source time on load; checked against the model and for round trips.
+//! - `round_trip_on_disk`: captions, settings and overrides survive
+//! project-config.json and the legacy captions.json sidecar.
+//! - `transcription_audio`: a fake transcriber hears the fixture's audio
+//! markers in the transcription input assembled the way the app does
+//! (per-take mic + system audio aligned by the clip offsets, takes
+//! concatenated by display duration) and returns one word per marker; every
+//! word must sit at its source time.
+//! - `render_*`: exports with captions; every output frame must show exactly
+//! the caption the model puts there (identified against per-text glyph
+//! templates), or none.
+//! - `editor_open`: opening a project in the editor engine migrates and
+//! re-projects stored captions as the model says.
+//!
+//! Reference model (documented rules of the caption projection, written for
+//! the test):
+//! - Source time is the recordings concatenated: clip `c` starts at the sum
+//! of the earlier clips' display durations.
+//! - A word's end is clamped to `start + 2.5 s`; a caption with words ends at
+//! its last clamped word.
+//! - Each caption is cut by every timeline segment, in timeline order: the
+//! part of each word inside the segment's source range (non-empty) is
+//! placed at `segment output start + (t - range start) / timescale` and
+//! moved past fullscreen-text holds (a range ending exactly at a hold ends
+//! before it). A piece spans its first to last word; its text joins the
+//! words with spaces, except before punctuation that attaches to the
+//! previous word. A caption without words maps its own range.
+//! - A caption cut into several pieces gets ids `<id>::edl<n>`; pieces are
+//! sorted by output start (stable); style overrides follow the source id.
+//! - Rendering: at output time `t` the first piece with
+//! `start <= t < min(end, last word start + 2.5)` is shown.
+
+mod common;
+mod edits;
+
+use std::path::Path;
+
+use cap_project::{
+ CaptionSegment, CaptionSettings, CaptionTrackSegment, CaptionWord, CaptionsData,
+ ProjectConfiguration, RecordingMeta, StudioRecordingMeta,
+};
+use cap_verify::{
+ audio_code::{self, AudioSource, MARKER_SECS},
+ catalog,
+ fixture::{AudioTrackSpec, FixtureSpec, Rng, SegmentSpec, Timing, VideoTrackSpec},
+ media,
+ report::{self, Case, Tier},
+ video_code::PixelSource,
+};
+use edits::{Op, OpMix, TimeModel};
+
+const MAX_WORD_SECS: f64 = 2.5;
+/// Projected times are stored as f32.
+const TIME_TOLERANCE: f64 = 1e-4;
+const WORD_TOLERANCE_SECS: f64 = 0.001;
+
+/// Settles a case, printing its notes (the core report prints them only in
+/// the JSON report).
+fn settle(case: Case) -> Option<String> {
+ for note in &case.notes {
+ eprintln!("[cap-verify] {}: {note}", case.id);
+ }
+ report::settle(case).err()
+}
+
+fn finish(case: Case) {
+ if let Some(message) = settle(case) {
+ panic!("{message}");
+ }
+}
+
+fn seeds(fast: u64, full: u64) -> u64 {
+ match report::tier() {
+ Tier::Fast => fast,
+ Tier::Full => full,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Reference model
+// ---------------------------------------------------------------------------
+
+fn attaches_to_previous(text: &str) -> bool {
+ const ATTACHING: &str = ",.!?;:%)]}'’、。!?;:,";
+ text.trim()
+ .chars()
+ .next()
+ .is_some_and(|c| ATTACHING.contains(c))
+}
+
+fn join_words<'a>(words: impl IntoIterator<Item = &'a str>) -> String {
+ let mut text = String::new();
+ for word in words.into_iter().map(str::trim).filter(|w| !w.is_empty()) {
+ if !text.is_empty() && !attaches_to_previous(word) {
+ text.push(' ');
+ }
+ text.push_str(word);
+ }
+ text
+}
+
+#[derive(Clone, Debug, Default)]
+struct Overrides {
+ fade: Option<f32>,
+ position: Option<String>,
+ color: Option<String>,
+ font_size: Option<u32>,
+}
+
+#[derive(Clone, Debug)]
+struct Piece {
+ id: String,
+ start: f64,
+ end: f64,
+ text: String,
+ words: Vec<(String, f64, f64)>,
+ overrides: Overrides,
+}
+
+impl Piece {
+ /// Where the renderer stops showing the piece.
+ fn visible_end(&self) -> f64 {
+ match self.words.last() {
+ Some(w) => self.end.min(w.1 + MAX_WORD_SECS),
+ None => self.end,
+ }
+ }
+}
+
+fn clip_starts(durations: &[f64]) -> Vec<f64> {
+ let mut starts = vec![0.0];
+ for d in durations {
+ starts.push(starts.last().unwrap() + d);
+ }
+ starts
+}
+
+/// Projects source-timed captions through `config`'s edit list.
+fn model_project(
+ captions: &[CaptionSegment],
+ config: &ProjectConfiguration,
+ durations: &[f64],
+) -> Vec<Piece> {
+ let time = TimeModel::new(config);
+ let starts = clip_starts(durations);
+ let mut overrides: Vec<(String, Overrides)> = Vec::new();
+ for t in &edits::timeline(config).caption_segments {
+ let source = t.id.split("::edl").next().unwrap_or(&t.id).to_string();
+ if !overrides.iter().any(|(id, _)| *id == source) {
+ overrides.push((
+ source,
+ Overrides {
+ fade: t.fade_duration_override,
+ position: t.position_override.clone(),
+ color: t.color_override.clone(),
+ font_size: t.font_size_override,
+ },
+ ));
+ }
+ }
+ let mut out = Vec::new();
+ for caption in captions {
+ let words: Vec<(String, f64, f64)> = caption
+ .words
+ .iter()
+ .map(|w| {
+ let start = f64::from(w.start);
+ let end = f64::from(w.end).min(start + MAX_WORD_SECS);
+ (w.text.clone(), start, end)
+ })
+ .collect();
+ let mut pieces = Vec::new();
+ for s in &time.segments {
+ let lo = starts[s.clip as usize] + s.start;
+ let hi = starts[s.clip as usize] + s.end;
+ let place = |a: f64, b: f64| -> Option<(f64, f64)> {
+ let (a, b) = (a.max(lo), b.min(hi));
+ (a < b).then(|| {
+ (
+ time.to_output(s.out_start + (a - lo) / s.timescale),
+ time.to_output_end(s.out_start + (b - lo) / s.timescale),
+ )
+ })
+ };
+ if words.is_empty() {
+ let end = f64::from(caption.end);
+ if let Some((a, b)) = place(f64::from(caption.start), end) {
+ pieces.push((a, b, caption.text.clone(), Vec::new()));
+ }
+ continue;
+ }
+ let placed: Vec<(String, f64, f64)> = words
+ .iter()
+ .filter_map(|(text, a, b)| place(*a, *b).map(|(a, b)| (text.clone(), a, b)))
+ .collect();
+ if let (Some(first), Some(last)) = (placed.first(), placed.last()) {
+ let text = join_words(placed.iter().map(|w| w.0.as_str()));
+ pieces.push((first.1, last.2, text, placed.clone()));
+ }
+ }
+ let count = pieces.len();
+ let source_overrides = overrides
+ .iter()
+ .find(|(id, _)| *id == caption.id)
+ .map(|(_, o)| o.clone())
+ .unwrap_or_default();
+ for (i, (start, end, text, words)) in pieces.into_iter().enumerate() {
+ out.push(Piece {
+ id: if count == 1 {
+ caption.id.clone()
+ } else {
+ format!("{}::edl{i}", caption.id)
+ },
+ start,
+ end,
+ text,
+ words,
+ overrides: source_overrides.clone(),
+ });
+ }
+ }
+ out.sort_by(|a, b| a.start.total_cmp(&b.start));
+ out
+}
+
+/// Moves output-timed (legacy) captions to source time: a caption keeps
+/// only if both ends map; unmappable words drop.
+fn model_migrate(
+ legacy: &[CaptionSegment],
+ config: &ProjectConfiguration,
+ durations: &[f64],
+) -> Vec<CaptionSegment> {
+ let time = TimeModel::new(config);
+ let starts = clip_starts(durations);
+ let to_source = |o: f32| time.output_to_source(f64::from(o), &starts);
+ let mut out: Vec<CaptionSegment> = legacy
+ .iter()
+ .filter_map(|c| {
+ Some(CaptionSegment {
+ id: c.id.clone(),
+ start: to_source(c.start)? as f32,
+ end: to_source(c.end)? as f32,
+ text: c.text.clone(),
+ words: c
+ .words
+ .iter()
+ .filter_map(|w| {
+ Some(CaptionWord {
+ text: w.text.clone(),
+ start: to_source(w.start)? as f32,
+ end: to_source(w.end)? as f32,
+ })
+ })
+ .collect(),
+ })
+ })
+ .collect();
+ out.sort_by(|a, b| a.start.total_cmp(&b.start));
+ out
+}
+
+fn close(a: f64, b: f64) -> bool {
+ (a - b).abs() <= TIME_TOLERANCE
+}
+
+fn describe(p: &Piece) -> String {
+ format!("{} {:.4}-{:.4} \"{}\"", p.id, p.start, p.end, p.text)
+}
+
+fn describe_track(t: &CaptionTrackSegment) -> String {
+ format!("{} {:.4}-{:.4} \"{}\"", t.id, t.start, t.end, t.text)
+}
+
+/// Indices of `starts` in output order, pieces starting together (within
+/// the time tolerance) ordered by id: which of two pieces that start
+/// together is listed first is not specified.
+fn tie_order(items: &[(f64, &str)]) -> Vec<usize> {
+ let mut order: Vec<usize> = (0..items.len()).collect();
+ order.sort_by(|&a, &b| items[a].0.total_cmp(&items[b].0));
+ let mut i = 0;
+ while i < order.len() {
+ let mut j = i + 1;
+ while j < order.len() && items[order[j]].0 - items[order[j - 1]].0 <= TIME_TOLERANCE {
+ j += 1;
+ }
+ order[i..j].sort_by(|&a, &b| items[a].1.cmp(items[b].1));
+ i = j;
+ }
+ order
+}
+
+/// Compares the engine's caption track with the model's pieces.
+fn compare_track(product: &[CaptionTrackSegment], model: &[Piece]) -> Vec<String> {
+ let product_order = tie_order(
+ &product
+ .iter()
+ .map(|p| (p.start, p.id.as_str()))
+ .collect::<Vec<_>>(),
+ );
+ let model_order = tie_order(
+ &model
+ .iter()
+ .map(|p| (p.start, p.id.as_str()))
+ .collect::<Vec<_>>(),
+ );
+ let product: Vec<&CaptionTrackSegment> = product_order.iter().map(|&i| &product[i]).collect();
+ let model: Vec<&Piece> = model_order.iter().map(|&i| &model[i]).collect();
+ let mut problems = Vec::new();
+ if product.len() != model.len() {
+ problems.push(format!(
+ "{} caption track segments, the model expects {}",
+ product.len(),
+ model.len()
+ ));
+ }
+ for (p, m) in product.iter().zip(&model) {
+ let words_match = p.words.len() == m.words.len()
+ && p.words.iter().zip(&m.words).all(|(a, b)| {
+ a.text == b.0 && close(f64::from(a.start), b.1) && close(f64::from(a.end), b.2)
+ });
+ let overrides_match = p.fade_duration_override == m.overrides.fade
+ && p.position_override == m.overrides.position
+ && p.color_override == m.overrides.color
+ && p.font_size_override == m.overrides.font_size;
+ if p.id != m.id
+ || !close(p.start, m.start)
+ || !close(p.end, m.end)
+ || p.text != m.text
+ || !words_match
+ || !overrides_match
+ {
+ problems.push(format!(
+ "engine {}{}, model {}",
+ describe_track(p),
+ if overrides_match {
+ ""
+ } else {
+ " (overrides differ)"
+ },
+ describe(m)
+ ));
+ }
+ }
+ problems
+}
+
+// ---------------------------------------------------------------------------
+// Random captions
+// ---------------------------------------------------------------------------
+
+const VOCABULARY: [&str; 24] = [
+ "hello", "world", "is", "a", "river", "cloud", "it", "to", "über", "café", "日本", "so",
+ "screen", "record", "of", "we", "on", "capture", "edit", "timeline", "in", "up", "my", "an",
+];
+const PUNCTUATION: [&str; 6] = [",", ".", "?", "!", "'s", "%"];
+
+fn random_captions(rng: &mut Rng, total: f64) -> Vec<CaptionSegment> {
+ let mut captions = Vec::new();
+ let mut t = rng.f64() * 0.5;
+ while t < total + 1.0 {
+ let id = format!("c{}", captions.len());
+ if rng.range(0, 9) == 0 {
+ let end = t + 0.2 + rng.f64() * 2.0;
+ captions.push(CaptionSegment {
+ id,
+ start: t as f32,
+ end: end as f32,
+ text: format!("plain text {}", captions.len()),
+ words: Vec::new(),
+ });
+ t = end + rng.f64() * 0.5;
+ continue;
+ }
+ let mut words = Vec::new();
+ for i in 0..rng.range(1, 8) {
+ if i > 0 {
+ t += match rng.range(0, 3) {
+ 0 => 0.0,
+ 1 => rng.f64() * 0.2,
+ 2 => rng.f64() * 0.6,
+ _ => rng.f64() * 1.5,
+ };
+ }
+ let length = if rng.range(0, 19) == 0 {
+ 3.0 + rng.f64() * 4.0
+ } else {
+ 0.05 + rng.f64() * 0.6
+ };
+ let text = if i > 0 && rng.range(0, 5) == 0 {
+ PUNCTUATION[rng.range(0, PUNCTUATION.len() as u64 - 1) as usize]
+ } else {
+ VOCABULARY[rng.range(0, VOCABULARY.len() as u64 - 1) as usize]
+ };
+ words.push(CaptionWord {
+ text: text.to_string(),
+ start: t as f32,
+ end: (t + length) as f32,
+ });
+ t += length;
+ }
+ let start = words[0].start;
+ let mut end = words.last().unwrap().end;
+ if rng.range(0, 3) == 0 {
+ end += (rng.f64() * 1.0) as f32;
+ }
+ captions.push(CaptionSegment {
+ id,
+ start,
+ end,
+ text: join_words(words.iter().map(|w| w.text.as_str())),
+ words,
+ });
+ t += rng.f64() * 1.2;
+ }
+ captions
+}
+
+fn caption_settings() -> CaptionSettings {
+ CaptionSettings {
+ enabled: true,
+ ..Default::default()
+ }
+}
+
+fn set_captions(
+ config: &mut ProjectConfiguration,
+ captions: Vec<CaptionSegment>,
+ source_timed: bool,
+) {
+ config.captions = Some(CaptionsData {
+ segments: captions,
+ settings: caption_settings(),
+ source_timed,
+ });
+}
+
+/// Style overrides on some current track pieces. `per_source` styles every
+/// piece of a caption alike; otherwise pieces of one caption may differ and
+/// the first piece's style is the one that survives re-projection.
+fn random_overrides(rng: &mut Rng, config: &mut ProjectConfiguration, per_source: bool) {
+ let timeline = config.timeline.as_mut().expect("timeline");
+ let mut styled: Vec<(String, CaptionTrackSegment)> = Vec::new();
+ for piece in &mut timeline.caption_segments {
+ let source = cap_project::source_caption_id(&piece.id).to_string();
+ if per_source && let Some((_, style)) = styled.iter().find(|(id, _)| *id == source) {
+ piece.fade_duration_override = style.fade_duration_override;
+ piece.position_override = style.position_override.clone();
+ piece.color_override = style.color_override.clone();
+ piece.font_size_override = style.font_size_override;
+ continue;
+ }
+ if rng.range(0, 3) == 0 {
+ piece.fade_duration_override = Some(rng.range(0, 5) as f32 / 10.0);
+ piece.position_override = Some("top-center".into());
+ piece.color_override = Some(format!("#{:06X}", rng.range(0, 0xFF_FFFF)));
+ piece.font_size_override = Some(rng.range(12, 96) as u32);
+ }
+ styled.push((source, piece.clone()));
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Projection and migration properties
+// ---------------------------------------------------------------------------
+
+fn projection_problems(
+ base: &ProjectConfiguration,
+ ops: &[Op],
+ captions: &[CaptionSegment],
+ durations: &[f64],
+ override_seed: u64,
+) -> Vec<String> {
+ let mut config = base.clone();
+ set_captions(&mut config, captions.to_vec(), true);
+ cap_project::synchronize_captions(&mut config, durations);
+ random_overrides(&mut Rng::new(override_seed), &mut config, false);
+ for op in ops {
+ edits::apply(&mut config, op);
+ }
+ let model = model_project(captions, &config, durations);
+ cap_project::synchronize_captions(&mut config, durations);
+ let mut problems = compare_track(&edits::timeline(&config).caption_segments, &model);
+ let again = edits::timeline(&config).caption_segments.clone();
+ cap_project::synchronize_captions(&mut config, durations);
+ let after = &edits::timeline(&config).caption_segments;
+ if serde_json::to_value(&again).ok() != serde_json::to_value(after).ok() {
+ problems.push("re-synchronizing an unchanged project changed the caption track".into());
+ }
+ problems
+}
+
+fn projection_case(name: &str, mix: OpMix, seeds: u64) {
+ let id = format!("captions/projection/{name}");
+ if !report::selected(&id) {
+ return;
+ }
+ let mut case = Case::new(&id);
+ let (mut failed, mut pieces) = (0, 0usize);
+ for seed in 0..seeds {
+ let mut rng = Rng::new(0xCA97_0000 ^ (seed << 8) ^ name.len() as u64);
+ let durations = edits::random_durations(&mut rng);
+ let base = edits::base_config(&durations);
+ let captions = random_captions(&mut rng, durations.iter().sum());
+ let count = rng.range(0, 8) as usize;
+ let ops = edits::random_sequence(&mut rng, &base, count, mix);
+ let problems = projection_problems(&base, &ops, &captions, &durations, seed);
+ pieces += model_project(&captions, &edits::replay(&base, &ops), &durations).len();
+ if problems.is_empty() {
+ continue;
+ }
+ failed += 1;
+ if failed > 3 {
+ continue;
+ }
+ let minimal = edits::shrink(&ops, |ops| {
+ !projection_problems(&base, ops, &captions, &durations, seed).is_empty()
+ });
+ let minimal_problems = projection_problems(&base, &minimal, &captions, &durations, seed);
+ case.problem(format!(
+ "seed {seed}: clips {durations:?}, {} captions, shrunk from {} to {} ops {minimal:?}: {} problems (first: {})",
+ captions.len(),
+ ops.len(),
+ minimal.len(),
+ minimal_problems.len(),
+ minimal_problems.iter().take(3).cloned().collect::<Vec<_>>().join("; ")
+ ));
+ }
+ case.note(format!(
+ "{seeds} random caption sets and edit sequences, {pieces} projected pieces, {failed} failed"
+ ));
+ if failed > 3 {
+ case.problem(format!("{failed} sequences failed in total"));
+ }
+ finish(case);
+}
+
+#[test]
+fn projection_cuts_speeds() {
+ projection_case(
+ "cuts-speeds",
+ OpMix {
+ transitions: false,
+ holds: false,
+ },
+ seeds(300, 3000),
+ );
+}
+
+#[test]
+fn projection_transitions() {
+ projection_case(
+ "transitions",
+ OpMix {
+ transitions: true,
+ holds: false,
+ },
+ seeds(300, 3000),
+ );
+}
+
+#[test]
+fn projection_holds() {
+ projection_case(
+ "holds",
+ OpMix {
+ transitions: false,
+ holds: true,
+ },
+ seeds(300, 3000),
+ );
+}
+
+#[test]
+fn projection_all() {
+ projection_case(
+ "all",
+ OpMix {
+ transitions: true,
+ holds: true,
+ },
+ seeds(300, 3000),
+ );
+}
+
+fn track_as_captions(track: &[CaptionTrackSegment]) -> Vec<CaptionSegment> {
+ track
+ .iter()
+ .map(|t| CaptionSegment {
+ id: t.id.clone(),
+ start: t.start as f32,
+ end: t.end as f32,
+ text: t.text.clone(),
+ words: t.words.clone(),
+ })
+ .collect()
+}
+
+fn migration_problems(
+ base: &ProjectConfiguration,
+ ops: &[Op],
+ captions: &[CaptionSegment],
+ durations: &[f64],
+) -> Vec<String> {
+ let mut config = edits::replay(base, ops);
+ set_captions(&mut config, captions.to_vec(), true);
+ cap_project::synchronize_captions(&mut config, durations);
+ let shown = edits::timeline(&config).caption_segments.clone();
+ let legacy = track_as_captions(&shown);
+ config
+ .timeline
+ .as_mut()
+ .expect("timeline")
+ .caption_segments
+ .clear();
+ set_captions(&mut config, legacy.clone(), false);
+ let expected = model_migrate(&legacy, &config, durations);
+ cap_project::synchronize_captions(&mut config, durations);
+ let captions_data = config.captions.as_ref().expect("captions");
+ let mut problems = Vec::new();
+ if !captions_data.source_timed {
+ problems.push("captions still marked output-timed after loading".into());
+ }
+ let migrated = &captions_data.segments;
+ if migrated.len() != expected.len() {
+ problems.push(format!(
+ "{} captions after migration, the model expects {}",
+ migrated.len(),
+ expected.len()
+ ));
+ }
+ for (a, b) in migrated.iter().zip(&expected) {
+ let same = a.id == b.id
+ && close(f64::from(a.start), f64::from(b.start))
+ && close(f64::from(a.end), f64::from(b.end))
+ && a.words.len() == b.words.len()
+ && a.words.iter().zip(&b.words).all(|(x, y)| {
+ x.text == y.text
+ && close(f64::from(x.start), f64::from(y.start))
+ && close(f64::from(x.end), f64::from(y.end))
+ });
+ if !same {
+ problems.push(format!(
+ "migrated {} {:.4}-{:.4}, model {} {:.4}-{:.4}",
+ a.id, a.start, a.end, b.id, b.start, b.end
+ ));
+ }
+ }
+ problems.extend(compare_track(
+ &edits::timeline(&config).caption_segments,
+ &model_project(&expected, &config, durations),
+ ));
+ // A legacy caption inside one segment, away from transitions and holds,
+ // must come back where it was.
+ let time = TimeModel::new(&config);
+ let track = &edits::timeline(&config).caption_segments;
+ for piece in &shown {
+ let inside = time.segments.iter().enumerate().any(|(k, s)| {
+ let next_in = time.segments.get(k + 1).map_or(0.0, |n| n.transition_in);
+ let lo = time.to_output(s.out_start + s.transition_in);
+ let hi = time.to_output_end(s.out_start + s.duration - next_in);
+ piece.start > lo + TIME_TOLERANCE
+ && piece.end < hi - TIME_TOLERANCE
+ && time.held_before(piece.end) == time.held_before(piece.start)
+ });
+ let clean = piece
+ .words
+ .iter()
+ .all(|w| f64::from(w.end - w.start) < MAX_WORD_SECS);
+ if inside
+ && clean
+ && !track.iter().any(|t| {
+ t.text == piece.text && close(t.start, piece.start) && close(t.end, piece.end)
+ })
+ {
+ problems.push(format!(
+ "legacy caption {} did not come back in place after loading",
+ describe_track(piece)
+ ));
+ }
+ }
+ problems
+}
+
+#[test]
+fn legacy_migration() {
+ let id = "captions/legacy-migration";
+ if !report::selected(id) {
+ return;
+ }
+ let mut case = Case::new(id);
+ let seeds = seeds(300, 3000);
+ let mut failed = 0;
+ for seed in 0..seeds {
+ let mut rng = Rng::new(0xCA97_1000 ^ (seed << 8));
+ let durations = edits::random_durations(&mut rng);
+ let base = edits::base_config(&durations);
+ let captions = random_captions(&mut rng, durations.iter().sum());
+ let count = rng.range(0, 8) as usize;
+ let ops = edits::random_sequence(
+ &mut rng,
+ &base,
+ count,
+ OpMix {
+ transitions: true,
+ holds: true,
+ },
+ );
+ if migration_problems(&base, &ops, &captions, &durations).is_empty() {
+ continue;
+ }
+ failed += 1;
+ if failed > 3 {
+ continue;
+ }
+ let minimal = edits::shrink(&ops, |ops| {
+ !migration_problems(&base, ops, &captions, &durations).is_empty()
+ });
+ let problems = migration_problems(&base, &minimal, &captions, &durations);
+ case.problem(format!(
+ "seed {seed}: clips {durations:?}, shrunk to ops {minimal:?}: {} problems (first: {})",
+ problems.len(),
+ problems
+ .iter()
+ .take(3)
+ .cloned()
+ .collect::<Vec<_>>()
+ .join("; ")
+ ));
+ }
+ case.note(format!("{seeds} legacy projects migrated, {failed} failed"));
+ if failed > 3 {
+ case.problem(format!("{failed} sequences failed in total"));
+ }
+ finish(case);
+}
+
+// ---------------------------------------------------------------------------
+// On-disk round trips
+// ---------------------------------------------------------------------------
+
+fn styled_settings(rng: &mut Rng) -> CaptionSettings {
+ CaptionSettings {
+ enabled: true,
+ font: ["System Sans-Serif", "System Serif", "System Monospace"][rng.range(0, 2) as usize]
+ .into(),
+ size: rng.range(12, 96) as u32,
+ color: "#12AB34".into(),
+ background_color: "#00C800".into(),
+ background_opacity: rng.range(0, 100) as u32,
+ position: "top-left".into(),
+ italic: true,
+ font_weight: 500,
+ outline: true,
+ outline_color: "#FF0000".into(),
+ export_with_subtitles: true,
+ highlight_color: "#0000FF".into(),
+ fade_duration: 0.3,
+ linger_duration: 0.7,
+ word_transition_duration: 0.1,
+ active_word_highlight: true,
+ manual_position: Some(cap_project::XY::new(0.25, 0.75)),
+ preset: "custom".into(),
+ animation: "pop".into(),
+ highlight_style: "pill".into(),
+ uppercase: true,
+ }
+}
+
+#[test]
+fn round_trip_on_disk() {
+ let id = "captions/round-trip";
+ if !report::selected(id) {
+ return;
+ }
+ let mut case = Case::new(id);
+ let dir = common::scratch_dir(id);
+ let seeds = seeds(20, 200);
+ for seed in 0..seeds {
+ let mut rng = Rng::new(0xCA97_2000 ^ seed);
+ let durations = edits::random_durations(&mut rng);
+ let base = edits::base_config(&durations);
+ let ops = edits::random_sequence(
+ &mut rng,
+ &base,
+ 4,
+ OpMix {
+ transitions: true,
+ holds: true,
+ },
+ );
+ let mut config = edits::replay(&base, &ops);
+ config.captions = Some(CaptionsData {
+ segments: random_captions(&mut rng, durations.iter().sum()),
+ settings: styled_settings(&mut rng),
+ source_timed: true,
+ });
+ cap_project::synchronize_captions(&mut config, &durations);
+ random_overrides(&mut rng, &mut config, true);
+ let project = dir.path().join(format!("seed-{seed}"));
+ std::fs::create_dir_all(&project).expect("project dir");
+ if let Err(e) = config.write(&project) {
+ case.problem(format!("seed {seed}: write failed: {e}"));
+ continue;
+ }
+ let loaded = match ProjectConfiguration::load(&project) {
+ Ok(loaded) => loaded,
+ Err(e) => {
+ case.problem(format!("seed {seed}: load failed: {e}"));
+ continue;
+ }
+ };
+ let json = |c: &ProjectConfiguration| {
+ (
+ serde_json::to_value(&c.captions).expect("captions json"),
+ serde_json::to_value(&edits::timeline(c).caption_segments).expect("track json"),
+ )
+ };
+ if json(&config) != json(&loaded) {
+ case.problem(format!(
+ "seed {seed}: captions changed through project-config.json"
+ ));
+ }
+ let mut resynced = loaded.clone();
+ cap_project::synchronize_captions(&mut resynced, &durations);
+ if json(&resynced) != json(&loaded) {
+ case.problem(format!(
+ "seed {seed}: re-projecting a loaded project changed its captions"
+ ));
+ }
+ }
+ // The legacy captions.json sidecar of older projects: output-timed
+ // captions with no track, picked up when project-config.json has none.
+ let project = common::project(&catalog::basic(report::tier()));
+ let copy = dir.path().join("sidecar.cap");
+ copy_project(&project.path, &copy);
+ let mut rng = Rng::new(0xCA97_2FFF);
+ let legacy = CaptionsData {
+ segments: random_captions(&mut rng, 5.0),
+ settings: styled_settings(&mut rng),
+ source_timed: false,
+ };
+ std::fs::write(
+ copy.join("captions.json"),
+ serde_json::to_string(&legacy).expect("sidecar json"),
+ )
+ .expect("write sidecar");
+ let meta = RecordingMeta::load_for_project(&copy).expect("meta");
+ let loaded = meta.project_config();
+ match &loaded.captions {
+ None => case.problem("captions.json sidecar was not loaded"),
+ Some(c) => {
+ if serde_json::to_value(c).ok() != serde_json::to_value(&legacy).ok() {
+ case.problem("captions.json sidecar loaded with different captions");
+ }
+ }
+ }
+ case.note(format!(
+ "{seeds} projects through project-config.json, plus the captions.json sidecar"
+ ));
+ finish(case);
+}
+
+fn copy_project(from: &Path, to: &Path) {
+ for entry in walk(from) {
+ let rel = entry.strip_prefix(from).expect("inside project");
+ let target = to.join(rel);
+ std::fs::create_dir_all(target.parent().expect("parent")).expect("mkdir");
+ std::fs::copy(&entry, &target).expect("copy");
+ }
+}
+
+fn walk(dir: &Path) -> Vec<std::path::PathBuf> {
+ let mut out = Vec::new();
+ for entry in std::fs::read_dir(dir).expect("read dir").flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ out.extend(walk(&path));
+ } else {
+ out.push(path);
+ }
+ }
+ out
+}
+
+// ---------------------------------------------------------------------------
+// Transcription input + fake transcriber
+// ---------------------------------------------------------------------------
+
+/// Two takes; every track starts at a different time, so the clip offsets
+/// matter (mic 0.25 s late, system audio 0.1 s early, display 0.05 s late).
+fn transcription_fixture() -> FixtureSpec {
+ let screen = |duration: f64, start_time: f64| {
+ let mut v = VideoTrackSpec::new(
+ catalog::SCREEN_W,
+ catalog::SCREEN_H,
+ 30,
+ Timing::Constant { duration },
+ );
+ v.start_time = start_time;
+ v
+ };
+ let audio = |source: AudioSource, duration: f64, start_time: f64| AudioTrackSpec {
+ source,
+ sample_rate: 48_000,
+ channels: if source == AudioSource::System { 2 } else { 1 },
+ duration,
+ start_time,
+ };
+ FixtureSpec {
+ name: "captions-takes".into(),
+ segments: vec![
+ SegmentSpec {
+ display: screen(5.0, 0.05),
+ camera: None,
+ mic: Some(audio(AudioSource::Mic, 5.0, 0.25)),
+ system_audio: Some(audio(AudioSource::System, 5.2, -0.1)),
+ },
+ SegmentSpec {
+ display: screen(4.0, 0.0),
+ camera: None,
+ mic: Some(audio(AudioSource::Mic, 4.0, 0.0)),
+ system_audio: None,
+ },
+ ],
+ }
+}
+
+const RATE: u32 = 48_000;
+
+/// Display durations as the recordings' containers report them: the length
+/// of each take on the concatenated source timeline. Checked against the
+/// spec (whole frames) to within one frame.
+fn display_durations(case: &mut Case, project: &common::Project, spec: &FixtureSpec) -> Vec<f64> {
+ let durations: Vec<f64> = cap_rendering::ProjectRecordingsMeta::new(
+ &project.path,
+ project.meta.studio_meta().expect("studio"),
+ )
+ .expect("recordings meta")
+ .segments
+ .iter()
+ .map(|s| s.display.duration)
+ .collect();
+ for (d, s) in durations.iter().zip(&spec.segments) {
+ let truth = s.display.timing.duration(s.display.fps);
+ if (d - truth).abs() > 1.0 / f64::from(s.display.fps) + 1e-6 {
+ case.problem(format!(
+ "display duration {d:.4}s, the track has {truth:.4}s of frames"
+ ));
+ }
+ }
+ durations
+}
+
+fn interleaved(decoded: &media::DecodedAudio) -> Vec<f32> {
+ let frames = decoded.channels.iter().map(Vec::len).min().unwrap_or(0);
+ let mut samples = Vec::with_capacity(frames * decoded.channels.len());
+ for i in 0..frames {
+ for channel in &decoded.channels {
+ samples.push(channel[i]);
+ }
+ }
+ samples
+}
+
+/// The transcription input, built the way the app's transcription does:
+/// per take, system audio then mic, aligned by the clip offsets, over the
+/// take's display duration; takes concatenated.
+fn transcription_audio(project: &common::Project) -> Vec<f32> {
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = project.meta.studio_meta() else {
+ panic!("multi-segment fixture");
+ };
+ let recordings = cap_rendering::ProjectRecordingsMeta::new(
+ &project.path,
+ project.meta.studio_meta().expect("studio"),
+ )
+ .expect("recordings meta");
+ let takes: Vec<cap_editor::TranscriptionAudioTake> = inner
+ .segments
+ .iter()
+ .zip(&recordings.segments)
+ .map(|(segment, recording)| {
+ let offsets = segment.calculate_audio_offsets();
+ let mut sources = Vec::new();
+ for (audio, offset) in [
+ (&segment.system_audio, offsets.system_audio),
+ (&segment.mic, offsets.mic),
+ ] {
+ let Some(audio) = audio else { continue };
+ let decoded =
+ media::decode_audio(&project.path.join(audio.path.as_str()), Some(RATE))
+ .expect("decode source audio");
+ sources.push(cap_editor::TranscriptionAudioSource {
+ samples: interleaved(&decoded),
+ channels: decoded.channels.len(),
+ offset_secs: f64::from(offset),
+ });
+ }
+ cap_editor::TranscriptionAudioTake {
+ display_duration_secs: recording.display.duration,
+ sources,
+ }
+ })
+ .collect();
+ cap_editor::assemble_transcription_audio(&takes, RATE).expect("assemble")
+}
+
+fn word_text(source: AudioSource, index: u32) -> String {
+ format!("{}{index}", source.name())
+}
+
+/// The fake transcriber: one word per audio marker heard, timed from the
+/// marker's chirp to its end.
+fn fake_transcribe(audio: &[f32]) -> Vec<CaptionWord> {
+ let mut words: Vec<CaptionWord> = [AudioSource::Mic, AudioSource::System]
+ .into_iter()
+ .flat_map(|source| {
+ audio_code::locate_markers(audio, RATE, source)
+ .into_iter()
+ .filter_map(move |m| {
+ Some(CaptionWord {
+ text: word_text(source, m.index?),
+ start: m.time_secs as f32,
+ end: (m.time_secs + MARKER_SECS) as f32,
+ })
+ })
+ })
+ .collect();
+ words.sort_by(|a, b| a.start.total_cmp(&b.start));
+ words
+}
+
+/// Where every marker must be heard, from each source file's own markers
+/// and the spec's track start times: a track sample at file time `m`
+/// happened at `track start + m`; a take's transcription time 0 is its
+/// latest track start, and takes follow each other by display length.
+fn expected_words(
+ project: &common::Project,
+ spec: &FixtureSpec,
+ durations: &[f64],
+) -> Vec<(String, f64)> {
+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = project.meta.studio_meta() else {
+ panic!("multi-segment fixture");
+ };
+ let mut take_start = 0.0;
+ let mut out = Vec::new();
+ for ((segment, seg_spec), &display) in inner.segments.iter().zip(&spec.segments).zip(durations)
+ {
+ let latest = [
+ Some(seg_spec.display.start_time),
+ seg_spec.mic.as_ref().map(|a| a.start_time),
+ seg_spec.system_audio.as_ref().map(|a| a.start_time),
+ ]
+ .into_iter()
+ .flatten()
+ .fold(f64::NEG_INFINITY, f64::max);
+ for (meta, track) in [
+ (&segment.mic, &seg_spec.mic),
+ (&segment.system_audio, &seg_spec.system_audio),
+ ] {
+ let (Some(meta), Some(track)) = (meta, track) else {
+ continue;
+ };
+ let decoded = media::decode_audio(&project.path.join(meta.path.as_str()), Some(RATE))
+ .expect("decode source audio");
+ for marker in audio_code::locate_markers(&decoded.mono(), RATE, track.source) {
+ let Some(index) = marker.index else { continue };
+ let t = track.start_time + decoded.start_secs + marker.time_secs - latest;
+ if t >= 0.0 && t + MARKER_SECS <= display {
+ out.push((word_text(track.source, index), take_start + t));
+ }
+ }
+ }
+ take_start += display;
+ }
+ out.sort_by(|a, b| a.1.total_cmp(&b.1));
+ out
+}
+
+#[test]
+fn transcription_audio_words() {
+ let id = "captions/transcription-audio/takes";
+ if !report::selected(id) {
+ return;
+ }
+ let spec = transcription_fixture();
+ let project = common::project(&spec);
+ let mut case = Case::new(id);
+ let durations = display_durations(&mut case, &project, &spec);
+ let words = fake_transcribe(&transcription_audio(&project));
+ let expected = expected_words(&project, &spec, &durations);
+ let mut problems = Vec::new();
+ let mut worst = 0.0f64;
+ for (text, time) in &expected {
+ let hits: Vec<&CaptionWord> = words
+ .iter()
+ .filter(|w| &w.text == text && (f64::from(w.start) - time).abs() < 0.05)
+ .collect();
+ match hits.as_slice() {
+ [w] => {
+ let error = f64::from(w.start) - time;
+ worst = worst.max(error.abs());
+ if error.abs() > WORD_TOLERANCE_SECS {
+ problems.push(format!("{text} at {:.4}s, expected {time:.4}s", w.start));
+ }
+ }
+ [] => problems.push(format!("{text} missing (expected at {time:.4}s)")),
+ _ => problems.push(format!("{text} heard {} times", hits.len())),
+ }
+ }
+ if words.len() != expected.len() {
+ problems.push(format!(
+ "{} words heard, {} expected",
+ words.len(),
+ expected.len()
+ ));
+ }
+ if expected.len() < 10 {
+ problems.push(format!("only {} reference words", expected.len()));
+ }
+ if problems.is_empty() {
+ case.note(format!(
+ "{} words at their source times (worst {:.3} ms)",
+ words.len(),
+ worst * 1000.0
+ ));
+ } else {
+ case.problem(format!(
+ "{} problems (first: {})",
+ problems.len(),
+ problems
+ .iter()
+ .take(4)
+ .cloned()
+ .collect::<Vec<_>>()
+ .join("; ")
+ ));
+ }
+ // The transcribed captions through a reorder of the two takes, projected
+ // with the spec's display lengths as the source of truth.
+ let captions: Vec<CaptionSegment> = words
+ .chunks(3)
+ .enumerate()
+ .map(|(i, chunk)| CaptionSegment {
+ id: format!("segment-{i}"),
+ start: chunk[0].start,
+ end: chunk[chunk.len() - 1].end,
+ text: join_words(chunk.iter().map(|w| w.text.as_str())),
+ words: chunk.to_vec(),
+ })
+ .collect();
+ let mut config = project.config();
+ config
+ .timeline
+ .as_mut()
+ .expect("timeline")
+ .segments
+ .reverse();
+ set_captions(&mut config, captions.clone(), true);
+ cap_project::synchronize_captions(&mut config, &durations);
+ let track_problems = compare_track(
+ &edits::timeline(&config).caption_segments,
+ &model_project(&captions, &config, &durations),
+ );
+ if !track_problems.is_empty() {
+ case.problem(format!(
+ "reordered takes: {} caption problems (first: {})",
+ track_problems.len(),
+ track_problems[0]
+ ));
+ }
+ finish(case);
+}
+
+// ---------------------------------------------------------------------------
+// Rendered captions
+// ---------------------------------------------------------------------------
+
+/// Caption style that is easy to find: an opaque green box with white text,
+/// no fades, animation or word highlight.
+fn render_settings() -> CaptionSettings {
+ CaptionSettings {
+ enabled: true,
+ size: 72,
+ color: "#FFFFFF".into(),
+ background_color: "#00C800".into(),
+ background_opacity: 100,
+ position: "bottom-center".into(),
+ outline: false,
+ fade_duration: 0.0,
+ animation: "none".into(),
+ active_word_highlight: false,
+ ..Default::default()
+ }
+}
+
+const WORDS: [&str; 30] = [
+ "apple", "river", "cloud", "stone", "maple", "tiger", "piano", "lemon", "orbit", "glass",
+ "honey", "zebra", "candle", "forest", "rocket", "violet", "marble", "tunnel", "pepper",
+ "falcon", "garden", "silver", "anchor", "button", "copper", "dragon", "eclipse", "fabric",
+ "harbor", "island",
+];
+
+/// Scripted words: three per caption, one caption every ~1.35 s, with a
+/// word stretched across a silence in the third caption.
+fn scripted_captions(total: f64) -> Vec<CaptionSegment> {
+ let mut captions = Vec::new();
+ let mut t = 0.2;
+ let mut word = 0;
+ while t + 1.2 < total && word + 3 <= WORDS.len() {
+ let mut words = Vec::new();
+ for i in 0..3 {
+ let start = t + 0.4 * i as f64;
+ let mut end = start + 0.35;
+ if captions.len() == 2 && i == 2 {
+ end = start + 6.0;
+ }
+ words.push(CaptionWord {
+ text: WORDS[word].into(),
+ start: start as f32,
+ end: end as f32,
+ });
+ word += 1;
+ }
+ captions.push(CaptionSegment {
+ id: format!("segment-{}", captions.len()),
+ start: words[0].start,
+ end: words[2].end,
+ text: join_words(words.iter().map(|w| w.text.as_str())),
+ words,
+ });
+ t += 1.35;
+ }
+ captions
+}
+
+#[derive(Clone)]
+struct CaptionPixels {
+ box_pixels: usize,
+ /// Bright (text) pixels inside the box's rows, full width.
+ glyphs: Vec<bool>,
+ bbox: Option<(usize, usize, usize, usize)>,
+}
+
+fn caption_pixels(view: &impl PixelSource) -> CaptionPixels {
+ let (w, h) = (view.width(), view.height());
+ let mut box_pixels = 0;
+ let mut bbox: Option<(usize, usize, usize, usize)> = None;
+ for y in h / 2..h {
+ for x in 0..w {
+ let (cb, cr) = view.chroma(x, y);
+ if cb < -35.0 && cr < -40.0 {
+ box_pixels += 1;
+ bbox = Some(match bbox {
+ None => (x, y, x, y),
+ Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x), y1.max(y)),
+ });
+ }
+ }
+ }
+ let glyphs = (h / 2..h)
+ .flat_map(|y| (0..w).map(move |x| (x, y)))
+ .map(|(x, y)| {
+ bbox.is_some_and(|(x0, y0, x1, y1)| x >= x0 && x <= x1 && y >= y0 && y <= y1)
+ && view.luma(x, y) > 170.0
+ })
+ .collect();
+ CaptionPixels {
+ box_pixels,
+ glyphs,
+ bbox,
+ }
+}
+
+fn iou(a: &[bool], b: &[bool]) -> f64 {
+ let (mut both, mut any) = (0usize, 0usize);
+ for (x, y) in a.iter().zip(b) {
+ both += usize::from(*x && *y);
+ any += usize::from(*x || *y);
+ }
+ if any == 0 {
+ 1.0
+ } else {
+ both as f64 / any as f64
+ }
+}
+
+/// A frame shows a caption box when this many box pixels are present.
+const BOX_PRESENT: usize = 200;
+const SAME_TEXT_IOU: f64 = 0.75;
+
+fn decode_captions(path: &Path) -> Vec<CaptionPixels> {
+ let mut frames = Vec::new();
+ media::decode_video(path, |picture| frames.push(caption_pixels(&picture.view())))
+ .expect("decode export");
+ frames
+}
+
+const RENDER_FPS: u32 = 30;
+const RENDER_RES: (u32, u32) = (480, 270);
+
+fn render_export(
+ rt: &tokio::runtime::Runtime,
+ project: &common::Project,
+ config: ProjectConfiguration,
+ out: &Path,
+) -> Result<Vec<CaptionPixels>, String> {
+ let run = common::ExportRun {
+ fps: RENDER_FPS,
+ resolution: RENDER_RES,
+ format: common::Format::Mp4,
+ decoder: common::Decoder::Default,
+ };
+ let path = rt.block_on(common::export(project, config, &run, out))?;
+ Ok(decode_captions(&path))
+}
+
+/// Glyph templates: every piece text rendered alone in its own window of an
+/// unedited timeline.
+fn templates(
+ rt: &tokio::runtime::Runtime,
+ project: &common::Project,
+ texts: &[String],
+ out: &Path,
+) -> Result<Vec<(String, CaptionPixels)>, String> {
+ let slot = 0.3;
+ let mut config = project.config();
+ config.camera.hide = true;
+ let captions: Vec<CaptionSegment> = texts
+ .iter()
+ .enumerate()
+ .map(|(i, text)| CaptionSegment {
+ id: format!("t{i}"),
+ start: (i as f64 * slot) as f32,
+ end: (i as f64 * slot + slot - 0.05) as f32,
+ text: text.clone(),
+ words: Vec::new(),
+ })
+ .collect();
+ config.captions = Some(CaptionsData {
+ segments: captions,
+ settings: render_settings(),
+ source_timed: true,
+ });
+ let duration = edits::timeline(&config).duration();
+ if texts.len() as f64 * slot > duration {
+ return Err(format!(
+ "{} templates do not fit in {duration:.1}s",
+ texts.len()
+ ));
+ }
+ let frames = render_export(rt, project, config, out)?;
+ texts
+ .iter()
+ .enumerate()
+ .map(|(i, text)| {
+ let frame = ((i as f64 * slot + 0.12) * f64::from(RENDER_FPS)).round() as usize;
+ let pixels = frames
+ .get(frame)
+ .filter(|p| p.box_pixels >= BOX_PRESENT)
+ .ok_or_else(|| format!("template \"{text}\" not rendered at frame {frame}"))?;
+ Ok((text.clone(), pixels.clone()))
+ })
+ .collect()
+}
+
+struct RenderEdit {
+ name: &'static str,
+ apply: fn(&mut ProjectConfiguration),
+ /// Apply the edit after the caption track was projected, leaving the
+ /// stored track stale (the export must re-project it).
+ stale_track: bool,
+}
+
+fn render_case(
+ spec: FixtureSpec,
+ edit: &RenderEdit,
+ rt: &tokio::runtime::Runtime,
+) -> Option<String> {
+ let id = format!("captions/render/{}/{}", spec.name, edit.name);
+ if !report::selected(&id) {
+ return None;
+ }
+ let project = common::project(&spec);
+ let mut case = Case::new(&id);
+ let durations = display_durations(&mut case, &project, &spec);
+ let captions = scripted_captions(durations.iter().sum());
+ let mut config = project.config();
+ config.camera.hide = true;
+ if !edit.stale_track {
+ (edit.apply)(&mut config);
+ }
+ config.captions = Some(CaptionsData {
+ segments: captions.clone(),
+ settings: render_settings(),
+ source_timed: true,
+ });
+ cap_project::synchronize_captions(&mut config, &durations);
+ if edit.stale_track {
+ (edit.apply)(&mut config);
+ }
+ let pieces = model_project(&captions, &config, &durations);
+ let dir = common::scratch_dir(&id);
+ let mut texts: Vec<String> = pieces.iter().map(|p| p.text.clone()).collect();
+ texts.sort();
+ texts.dedup();
+ let result =
+ templates(rt, &project, &texts, &dir.path().join("templates.mp4")).and_then(|templates| {
+ render_export(rt, &project, config.clone(), &dir.path().join("out.mp4"))
+ .map(|frames| (templates, frames))
+ });
+ match result {
+ Err(e) => case.problem(format!("export failed: {e}")),
+ Ok((templates, frames)) => {
+ let time = TimeModel::new(&config);
+ let expected_frames = (time.duration() * f64::from(RENDER_FPS)).ceil() as usize;
+ if frames.len() != expected_frames {
+ case.problem(format!(
+ "{} frames, the timeline needs {expected_frames}",
+ frames.len()
+ ));
+ }
+ let mut wrong = Vec::new();
+ let (mut checked, mut shown) = (0, 0);
+ for (i, pixels) in frames.iter().enumerate() {
+ let t = i as f64 / f64::from(RENDER_FPS);
+ let edge = pieces
+ .iter()
+ .any(|p| (t - p.start).abs() < 1e-3 || (t - p.visible_end()).abs() < 1e-3);
+ if edge {
+ continue;
+ }
+ checked += 1;
+ let expected = pieces
+ .iter()
+ .find(|p| t >= p.start && t < p.visible_end())
+ .map(|p| p.text.as_str());
+ let present = pixels.box_pixels >= BOX_PRESENT;
+ let seen = present.then(|| {
+ templates
+ .iter()
+ .map(|(text, template)| {
+ (text.as_str(), iou(&template.glyphs, &pixels.glyphs))
+ })
+ .max_by(|a, b| a.1.total_cmp(&b.1))
+ .filter(|(_, score)| *score >= SAME_TEXT_IOU)
+ .map(|(text, _)| text)
+ });
+ let ok = match (expected, seen) {
+ (None, None) => true,
+ (Some(e), Some(Some(s))) => e == s,
+ _ => false,
+ };
+ shown += usize::from(expected.is_some());
+ if !ok {
+ wrong.push(format!(
+ "frame {i} ({t:.3}s): expected {expected:?}, shows {}",
+ match seen {
+ None => "no caption".to_string(),
+ Some(None) => format!("an unknown caption (box {:?})", pixels.bbox),
+ Some(Some(s)) => format!("\"{s}\""),
+ }
+ ));
+ }
+ }
+ let summary = format!(
+ "{} pieces, {checked} frames checked, {shown} with a caption",
+ pieces.len()
+ );
+ if wrong.is_empty() {
+ case.note(summary);
+ } else {
+ case.problem(format!(
+ "{summary}; {} frames wrong (first: {})",
+ wrong.len(),
+ wrong.iter().take(4).cloned().collect::<Vec<_>>().join("; ")
+ ));
+ }
+ }
+ }
+ settle(case)
+}
+
+fn render_edits() -> Vec<RenderEdit> {
+ vec![
+ RenderEdit {
+ name: "full",
+ apply: |_| {},
+ stale_track: false,
+ },
+ RenderEdit {
+ name: "cuts-speeds-reorder",
+ apply: |c| {
+ common::set_cuts(
+ c,
+ &[
+ (0.5, 2.0, 1.0),
+ (2.5, 4.0, 2.0),
+ (1.0, 2.0, 0.5),
+ (4.0, 5.8, 1.5),
+ ],
+ )
+ },
+ stale_track: false,
+ },
+ RenderEdit {
+ name: "transition",
+ apply: |c| {
+ common::set_cuts(c, &[(0.0, 2.5, 1.0), (3.5, 6.0, 1.0)]);
+ common::add_transition(c, 1, 0.4);
+ },
+ stale_track: false,
+ },
+ RenderEdit {
+ name: "stale-track",
+ apply: |c| common::set_cuts(c, &[(2.7, 6.0, 1.0), (0.0, 2.0, 1.0)]),
+ stale_track: true,
+ },
+ ]
+}
+
+#[test]
+fn render_single_clip() {
+ let rt = common::runtime();
+ let failures: Vec<String> = render_edits()
+ .iter()
+ .filter_map(|edit| render_case(catalog::basic(report::tier()), edit, &rt))
+ .collect();
+ common::assert_passed(failures);
+}
+
+#[test]
+fn render_multi_clip() {
+ let rt = common::runtime();
+ let edit = RenderEdit {
+ name: "reorder",
+ apply: |c| {
+ let timeline = c.timeline.as_mut().expect("timeline");
+ timeline.segments.reverse();
+ },
+ stale_track: true,
+ };
+ let failures: Vec<String> = render_case(catalog::multi_segment(report::tier()), &edit, &rt)
+ .into_iter()
+ .collect();
+ common::assert_passed(failures);
+}
+
+// ---------------------------------------------------------------------------
+// Opening a project in the editor
+// ---------------------------------------------------------------------------
+
+/// Opens a copy of `project` whose stored config is `config` in the editor
+/// engine and returns the config it settles on.
+fn open_in_editor(
+ rt: &tokio::runtime::Runtime,
+ project: &common::Project,
+ config: &ProjectConfiguration,
+ dir: &Path,
+ sidecar: Option<&CaptionsData>,
+) -> Result<ProjectConfiguration, String> {
+ let copy = dir.join("project.cap");
+ copy_project(&project.path, &copy);
+ config
+ .write(&copy)
+ .map_err(|e| format!("write config: {e}"))?;
+ if let Some(sidecar) = sidecar {
+ std::fs::write(
+ copy.join("captions.json"),
+ serde_json::to_string(sidecar).expect("sidecar json"),
+ )
+ .map_err(|e| format!("write sidecar: {e}"))?;
+ }
+ rt.block_on(async {
+ let editor = cap_editor::EditorInstance::new(
+ copy.clone(),
+ |_| {},
+ Box::new(|_: cap_editor::EditorFrameOutput, _: cap_editor::FrameLayout| {}),
+ None,
+ )
+ .await?;
+ let loaded = editor.project_config.1.borrow().clone();
+ editor.dispose().await;
+ Ok(loaded)
+ })
+}
+
+#[test]
+fn editor_open() {
+ let rt = common::runtime();
+ let spec = catalog::multi_segment(report::tier());
+ let project = common::project(&spec);
+ let mut durations_check = Case::new("captions/editor-open/durations");
+ let durations = display_durations(&mut durations_check, &project, &spec);
+ let mut rng = Rng::new(0xCA97_3000);
+ let captions = random_captions(&mut rng, durations.iter().sum());
+ let edit = |config: &mut ProjectConfiguration| {
+ let timeline = config.timeline.as_mut().expect("timeline");
+ timeline.segments.reverse();
+ timeline.segments[0].start += 0.5;
+ timeline.segments[1].timescale = 1.5;
+ };
+ let mut failures = Vec::new();
+ for variant in [
+ "source-timed-stale-track",
+ "legacy-output-timed",
+ "legacy-sidecar",
+ ] {
+ let id = format!("captions/editor-open/{variant}");
+ if !report::selected(&id) {
+ continue;
+ }
+ let mut case = Case::new(&id);
+ for problem in &durations_check.problems {
+ case.problem(problem.clone());
+ }
+ let dir = common::scratch_dir(&id);
+ let mut config = project.config();
+ let (expected_captions, sidecar) = match variant {
+ "source-timed-stale-track" => {
+ set_captions(&mut config, captions.clone(), true);
+ cap_project::synchronize_captions(&mut config, &durations);
+ edit(&mut config);
+ (captions.clone(), None)
+ }
+ _ => {
+ edit(&mut config);
+ let mut shown = config.clone();
+ set_captions(&mut shown, captions.clone(), true);
+ cap_project::synchronize_captions(&mut shown, &durations);
+ let legacy = track_as_captions(&edits::timeline(&shown).caption_segments);
+ let migrated = model_migrate(&legacy, &config, &durations);
+ if variant == "legacy-output-timed" {
+ set_captions(&mut config, legacy, false);
+ (migrated, None)
+ } else {
+ let sidecar = CaptionsData {
+ segments: legacy,
+ settings: caption_settings(),
+ source_timed: false,
+ };
+ (migrated, Some(sidecar))
+ }
+ }
+ };
+ match open_in_editor(&rt, &project, &config, dir.path(), sidecar.as_ref()) {
+ Err(e) => case.problem(format!("editor failed to open: {e}")),
+ Ok(loaded) => match &loaded.captions {
+ None => case.problem("no captions after opening"),
+ Some(data) => {
+ if !data.source_timed {
+ case.problem("captions still output-timed after opening");
+ }
+ let same = data.segments.len() == expected_captions.len()
+ && data.segments.iter().zip(&expected_captions).all(|(a, b)| {
+ a.id == b.id
+ && close(f64::from(a.start), f64::from(b.start))
+ && close(f64::from(a.end), f64::from(b.end))
+ && a.words.len() == b.words.len()
+ });
+ if !same {
+ case.problem(format!(
+ "stored captions after opening differ from the model ({} vs {})",
+ data.segments.len(),
+ expected_captions.len()
+ ));
+ }
+ let problems = compare_track(
+ &edits::timeline(&loaded).caption_segments,
+ &model_project(&expected_captions, &loaded, &durations),
+ );
+ if problems.is_empty() {
+ case.note(format!(
+ "{} captions, {} track pieces as the model says",
+ data.segments.len(),
+ edits::timeline(&loaded).caption_segments.len()
+ ));
+ } else {
+ case.problem(format!(
+ "{} track problems (first: {})",
+ problems.len(),
+ problems[0]
+ ));
+ }
+ }
+ },
+ }
+ failures.extend(settle(case));
+ }
+ common::assert_passed(failures);
+}
diff --git a/crates/verify/tests/editing.rs b/crates/verify/tests/editing.rs
new file mode 100644
index 000000000..335ccd9ba
--- /dev/null
+++ b/crates/verify/tests/editing.rs
@@ -0,0 +1,435 @@
+//! Editing oracle: seeded random sequences of timeline edits (split, delete,
+//! trim start/end, speed, reorder, clip volume, clip transitions, fullscreen
+//! text holds) on project configs.
+//!
+//! - `mapping_*`: for every sequence, the engine's timeline mapping
+//! (`TimelineConfiguration::duration`, `get_frame_mapping`,
+//! `get_segment_time`) must agree with the independent model in
+//! `edits::TimeModel` on a 1/60 s grid, at random times and just inside
+//! every edge; without holds, also with the core reference model
+//! (`cap_verify::model`). Failing sequences are shrunk to a minimal list
+//! of ops before reporting.
+//! - `export_*`: a few random edit sequences per fixture exported and
+//! checked frame for frame against the core reference model.
+//!
+//! Undo/redo lives in the desktop app (`ProjectHistory` snapshots whole
+//! project configs), not in an engine crate, so it is out of scope here.
+
+mod common;
+mod edits;
+
+use cap_project::ProjectConfiguration;
+use cap_verify::{
+ catalog,
+ fixture::Rng,
+ model::ReferenceModel,
+ report::{self, Case, Tier},
+};
+use common::{Decoder, ExportRun, Format};
+use edits::{Mapping, Op, OpMix, TimeModel};
+
+const TOLERANCE: f64 = 1e-9;
+const EDGE_EPSILON: f64 = 1e-6;
+
+/// Output times to probe: a 1/60 s grid, random times and both sides of
+/// every edge.
+fn probe_times(model: &TimeModel, rng: &mut Rng) -> Vec<f64> {
+ let duration = model.duration();
+ let mut times: Vec<f64> = (0..(duration * 60.0).ceil() as usize)
+ .map(|i| i as f64 / 60.0)
+ .collect();
+ times.extend((0..64).map(|_| rng.f64() * duration));
+ let mut edges = Vec::new();
+ for (k, s) in model.segments.iter().enumerate() {
+ let next_in = model.segments.get(k + 1).map_or(0.0, |n| n.transition_in);
+ for e in [
+ s.out_start,
+ s.out_start + s.transition_in,
+ s.out_start + s.duration - next_in,
+ ] {
+ edges.push(model.to_output(e));
+ }
+ }
+ for &(a, b) in &model.holds {
+ edges.extend([a, b]);
+ }
+ for edge in edges {
+ times.extend([edge - 1e-4, edge + 1e-4]);
+ }
+ times.retain(|&t| t >= 0.0 && t < duration);
+ times
+}
+
+#[derive(Clone, Copy, PartialEq)]
+enum Check {
+ /// Engine mapping against the models.
+ Mapping,
+ /// Every output time inside `duration()` has a source frame.
+ Coverage,
+}
+
+/// Checks one edited config; returns the problems.
+fn check_config(
+ config: &ProjectConfiguration,
+ durations: &[f64],
+ seed: u64,
+ check: Check,
+) -> Vec<String> {
+ let timeline = edits::timeline(config);
+ let model = TimeModel::new(config);
+ let mut problems = Vec::new();
+ if check == Check::Coverage {
+ let mut rng = Rng::new(seed);
+ for t in probe_times(&model, &mut rng) {
+ if !model.near_edge(t, EDGE_EPSILON) && timeline.get_frame_mapping(t).is_none() {
+ problems.push(format!(
+ "t={t:.6}: no source frame inside the {:.6}s timeline",
+ timeline.duration()
+ ));
+ }
+ }
+ return problems;
+ }
+ if (timeline.duration() - model.duration()).abs() > TOLERANCE {
+ problems.push(format!(
+ "duration {:.9}, the model expects {:.9}",
+ timeline.duration(),
+ model.duration()
+ ));
+ }
+ let core = if model.holds.is_empty() {
+ let (meta, truth) = edits::synthetic_meta(durations);
+ Some(ReferenceModel::new(&meta, config, truth).expect("core model"))
+ } else {
+ None
+ };
+ let mut rng = Rng::new(seed ^ 0x7123_4567);
+ for t in probe_times(&model, &mut rng) {
+ if model.near_edge(t, EDGE_EPSILON) {
+ continue;
+ }
+ let expected = model.map(t);
+ let actual = edits::product_map(timeline, t);
+ match (&expected, &actual) {
+ (Some(e), Some(a)) if edits::same_mapping(e, a, TOLERANCE) => {}
+ (None, None) => {}
+ _ => problems.push(format!("t={t:.6}: engine {actual:?}, model {expected:?}")),
+ }
+ let shown = config.get_segment_time(t).map(|(time, segment)| {
+ let index = timeline
+ .segments
+ .iter()
+ .position(|s| std::ptr::eq(s, segment))
+ .expect("segment from this timeline");
+ (index, time)
+ });
+ let expected_shown = expected.map(|m| (m.shown().segment, m.shown().time));
+ let shown_ok = match (shown, expected_shown) {
+ (Some((a, x)), Some((b, y))) => a == b && (x - y).abs() <= TOLERANCE,
+ (None, None) => true,
+ _ => false,
+ };
+ if !shown_ok {
+ problems.push(format!(
+ "t={t:.6}: get_segment_time {shown:?}, model {expected_shown:?}"
+ ));
+ }
+ if let (Some(core), Some(Mapping::Single { source, .. })) = (&core, &expected) {
+ let clip = timeline.segments[source.segment].recording_clip as usize;
+ match core.expect_at(t).source {
+ Some((c, time)) if c == clip && (time - source.time).abs() <= TOLERANCE => {}
+ other => problems.push(format!(
+ "t={t:.6}: core reference model {other:?}, edit model clip {clip} at {:.9}",
+ source.time
+ )),
+ }
+ }
+ }
+ problems
+}
+
+fn mapping_case(name: &str, mix: OpMix, seeds: u64, check: Check) {
+ let id = format!("editing/mapping/{name}");
+ if !report::selected(&id) {
+ return;
+ }
+ let mut case = Case::new(&id);
+ let mut failed = 0;
+ let mut probes = 0usize;
+ for seed in 0..seeds {
+ let mut rng = Rng::new(0xED17_0000 ^ (seed << 8) ^ name.len() as u64);
+ let durations = edits::random_durations(&mut rng);
+ let base = edits::base_config(&durations);
+ let count = rng.range(1, 10) as usize;
+ let ops = edits::random_sequence(&mut rng, &base, count, mix);
+ let config = edits::replay(&base, &ops);
+ probes += probe_times(&TimeModel::new(&config), &mut Rng::new(seed)).len();
+ let problems = check_config(&config, &durations, seed, check);
+ if problems.is_empty() {
+ continue;
+ }
+ failed += 1;
+ if failed > 3 {
+ continue;
+ }
+ let minimal = edits::shrink(&ops, |ops| {
+ !check_config(&edits::replay(&base, ops), &durations, seed, check).is_empty()
+ });
+ let minimal_problems =
+ check_config(&edits::replay(&base, &minimal), &durations, seed, check);
+ case.problem(format!(
+ "seed {seed}: clips {durations:?}, shrunk from {} to {} ops {minimal:?}: {} mismatches (first: {})",
+ ops.len(),
+ minimal.len(),
+ minimal_problems.len(),
+ minimal_problems
+ .iter()
+ .take(3)
+ .cloned()
+ .collect::<Vec<_>>()
+ .join("; ")
+ ));
+ }
+ case.note(format!(
+ "{seeds} random edit sequences, {probes} probe times, {failed} sequences failed"
+ ));
+ if failed > 3 {
+ case.problem(format!("{failed} sequences failed in total"));
+ }
+ finish(case);
+}
+
+/// Settles a case, printing its notes (the core report prints them only in
+/// the JSON report).
+fn settle(case: Case) -> Option<String> {
+ for note in &case.notes {
+ eprintln!("[cap-verify] {}: {note}", case.id);
+ }
+ report::settle(case).err()
+}
+
+fn finish(case: Case) {
+ if let Some(message) = settle(case) {
+ panic!("{message}");
+ }
+}
+
+fn seeds(fast: u64, full: u64) -> u64 {
+ match report::tier() {
+ Tier::Fast => fast,
+ Tier::Full => full,
+ }
+}
+
+#[test]
+fn mapping_cuts_speeds() {
+ mapping_case(
+ "cuts-speeds",
+ OpMix {
+ transitions: false,
+ holds: false,
+ },
+ seeds(300, 3000),
+ Check::Mapping,
+ );
+}
+
+#[test]
+fn mapping_transitions() {
+ mapping_case(
+ "transitions",
+ OpMix {
+ transitions: true,
+ holds: false,
+ },
+ seeds(300, 3000),
+ Check::Mapping,
+ );
+}
+
+#[test]
+fn mapping_holds() {
+ mapping_case(
+ "holds",
+ OpMix {
+ transitions: false,
+ holds: true,
+ },
+ seeds(300, 3000),
+ Check::Mapping,
+ );
+}
+
+#[test]
+fn mapping_all() {
+ mapping_case(
+ "all",
+ OpMix {
+ transitions: true,
+ holds: true,
+ },
+ seeds(300, 3000),
+ Check::Mapping,
+ );
+}
+
+/// Fullscreen text holds left past the end of the clips (place a text card,
+/// then trim or delete clips) still count towards `duration()`, but those
+/// output times have no source frame, so renders stop early.
+#[test]
+fn mapping_duration_covered() {
+ mapping_case(
+ "duration-covered",
+ OpMix {
+ transitions: true,
+ holds: true,
+ },
+ seeds(300, 3000),
+ Check::Coverage,
+ );
+}
+
+/// Random edits of a real fixture exported and checked frame by frame.
+fn export_cases(spec: cap_verify::fixture::FixtureSpec, seeds: u64) -> Vec<String> {
+ let project = common::project(&spec);
+ let base = project.config();
+ let rt = common::runtime();
+ let fps = 30;
+ let decoders = Decoder::all();
+ let mut failures = Vec::new();
+ for seed in 0..seeds {
+ let id = format!("editing/export/{}/seed-{seed}", spec.name);
+ if !report::selected(&id) {
+ continue;
+ }
+ let mut rng = Rng::new(0xED17_1000 ^ (seed << 8) ^ spec.name.len() as u64);
+ let count = rng.range(3, 8) as usize;
+ let ops = edits::random_sequence(
+ &mut rng,
+ &base,
+ count,
+ OpMix {
+ transitions: true,
+ holds: false,
+ },
+ );
+ let config = edits::replay(&base, &ops);
+ let mut case = Case::new(&id);
+ case.note(format!("ops: {ops:?}"));
+ let model = project.model(&config);
+ let dir = common::scratch_dir(&id);
+ let run = ExportRun {
+ fps,
+ resolution: (320, 180),
+ format: Format::Mp4,
+ decoder: decoders[seed as usize % decoders.len()],
+ };
+ case.note(format!("decoder {}", run.decoder.label()));
+ match rt.block_on(common::export(
+ &project,
+ config,
+ &run,
+ &dir.path().join("out.mp4"),
+ )) {
+ Err(e) => case.problem(format!("export failed: {e}")),
+ Ok(out) => {
+ let frames = common::read_output(&out);
+ common::check_sequence(&mut case, &model, &frames, fps, true);
+ }
+ }
+ failures.extend(settle(case));
+ }
+ failures
+}
+
+#[test]
+fn export_single_clip() {
+ common::assert_passed(export_cases(catalog::basic(report::tier()), seeds(8, 40)));
+}
+
+#[test]
+fn export_multi_clip() {
+ common::assert_passed(export_cases(
+ catalog::multi_segment(report::tier()),
+ seeds(6, 30),
+ ));
+}
+
+/// Deterministic repro for `editing/mapping/duration-covered`: a 1 s
+/// fullscreen text card at 5.4 s, then the clip trimmed to 3.2 s. The
+/// timeline reports 4.2 s; the export must have as many frames.
+#[test]
+fn hold_past_end_export() {
+ let id = "editing/export/hold-past-end";
+ if !report::selected(id) {
+ return;
+ }
+ let project = common::project(&catalog::basic(report::tier()));
+ let mut config = project.config();
+ let timeline = config.timeline.as_mut().expect("timeline");
+ timeline
+ .text_segments
+ .push(edits::fullscreen_text(5.4, 6.4));
+ timeline.segments[0].end = 3.2;
+ let duration = timeline.duration();
+ let fps = 30;
+ let mut case = Case::new(id);
+ let dir = common::scratch_dir(id);
+ let run = ExportRun {
+ fps,
+ resolution: (320, 180),
+ format: Format::Mp4,
+ decoder: Decoder::Default,
+ };
+ match common::runtime().block_on(common::export(
+ &project,
+ config,
+ &run,
+ &dir.path().join("out.mp4"),
+ )) {
+ Err(e) => case.problem(format!("export failed: {e}")),
+ Ok(out) => {
+ let frames = common::read_output(&out).len();
+ let expected = (duration * f64::from(fps)).ceil() as usize;
+ if frames == expected {
+ case.note(format!("{frames} frames for the {duration:.3}s timeline"));
+ } else {
+ case.problem(format!(
+ "{frames} frames exported, the {duration:.3}s timeline needs {expected}"
+ ));
+ }
+ }
+ }
+ finish(case);
+}
+
+#[test]
+fn shrinker_finds_the_minimal_sequence() {
+ let base = edits::base_config(&[6.0]);
+ let ops = vec![
+ Op::Volume {
+ segment: 0,
+ volume: 0.5,
+ },
+ Op::Split {
+ segment: 0,
+ at: 0.5,
+ },
+ Op::Speed {
+ segment: 1,
+ timescale: 2.0,
+ },
+ Op::Move { from: 0, to: 1 },
+ ];
+ let fails = |ops: &[Op]| {
+ let config = edits::replay(&base, ops);
+ edits::timeline(&config)
+ .segments
+ .first()
+ .is_some_and(|s| s.timescale == 2.0)
+ };
+ assert!(fails(&ops));
+ let minimal = edits::shrink(&ops, fails);
+ assert_eq!(minimal.len(), 3, "{minimal:?}");
+ assert!(!minimal.iter().any(|op| matches!(op, Op::Volume { .. })));
+}
diff --git a/crates/verify/tests/edits/mod.rs b/crates/verify/tests/edits/mod.rs
new file mode 100644
index 000000000..53898427a
--- /dev/null
+++ b/crates/verify/tests/edits/mod.rs
@@ -0,0 +1,734 @@
+//! Random timeline edits shared by `editing.rs` and `captions.rs`.
+//!
+//! - [`Op`]: one user edit (split, delete, trim, speed, reorder, clip
+//! volume, clip transition, fullscreen text hold). Parameters are
+//! fractions, so any sub-sequence of a recorded sequence replays to a valid
+//! project; an op that no longer applies is skipped. That makes failures
+//! shrinkable: [`shrink`] drops ops while the failure persists.
+//! - [`TimeModel`]: an independent model of the output -> recording mapping,
+//! written from the documented rules rather than by calling
+//! `cap_project`:
+//! - segments play back to back; segment `k` lasts
+//! `(end - start) / timescale` and maps `u` seconds into it to recording
+//! time `start + u * timescale`;
+//! - a clip transition into `k` overlaps `k - 1` and `k` by its duration,
+//! clamped to `[0.05, min(dur(k - 1), dur(k)) / 2]` and dropped when that
+//! range is empty; inside it both sides play, `k - 1` from
+//! `dur(k - 1) - transition` on;
+//! - enabled fullscreen text segments are holds: the recording clock
+//! pauses for their output-time window (overlapping or touching windows
+//! merge), showing the frame at the hold start; the timeline grows by the
+//! held time.
+
+#![allow(dead_code)]
+
+use cap_project::{
+ ClipConfiguration, ClipTransition, ClipTransitionType, MultipleSegment, MultipleSegments,
+ Platform, ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta,
+ StudioRecordingStatus, TextSegment, TimelineConfiguration, TimelineFrameMapping,
+ TimelineSegment, VideoMeta,
+};
+use cap_verify::fixture::{Rng, SegmentTruth, SourceFrame, SourceTruth, TrackTruth};
+use cap_verify::video_code::StreamKind;
+use relative_path::RelativePathBuf;
+
+/// No edit leaves a timeline segment shorter than this (recording seconds).
+pub const MIN_SOURCE: f64 = 0.4;
+pub const MIN_TRANSITION: f64 = 0.05;
+const SPEEDS: [f64; 6] = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Op {
+ Split { segment: usize, at: f64 },
+ Delete { segment: usize },
+ TrimStart { segment: usize, by: f64 },
+ TrimEnd { segment: usize, by: f64 },
+ Speed { segment: usize, timescale: f64 },
+ Move { from: usize, to: usize },
+ Volume { segment: usize, volume: f64 },
+ Transition { segment: usize, duration: f64 },
+ Hold { at: f64, length: f64 },
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct OpMix {
+ pub transitions: bool,
+ pub holds: bool,
+}
+
+pub fn timeline(config: &ProjectConfiguration) -> &TimelineConfiguration {
+ config.timeline.as_ref().expect("timeline")
+}
+
+fn timeline_mut(config: &mut ProjectConfiguration) -> &mut TimelineConfiguration {
+ config.timeline.as_mut().expect("timeline")
+}
+
+fn source_len(segment: &TimelineSegment) -> f64 {
+ segment.end - segment.start
+}
+
+/// Keeps transitions sorted, one per boundary, on boundaries that exist.
+fn tidy_transitions(timeline: &mut TimelineConfiguration) {
+ let count = timeline.segments.len();
+ timeline
+ .transitions
+ .retain(|t| t.segment_index >= 1 && (t.segment_index as usize) < count);
+ timeline.transitions.sort_by_key(|t| t.segment_index);
+ timeline
+ .transitions
+ .dedup_by(|later, earlier| later.segment_index == earlier.segment_index);
+}
+
+/// Applies `op`; false when it does not apply to this project (it is then
+/// skipped, which keeps every sub-sequence replayable).
+pub fn apply(config: &mut ProjectConfiguration, op: &Op) -> bool {
+ let total = timeline(config).duration();
+ let timeline = timeline_mut(config);
+ let count = timeline.segments.len();
+ let valid = |index: usize| index < count;
+ match *op {
+ Op::Split { segment, at } => {
+ if !valid(segment) || source_len(&timeline.segments[segment]) < 2.0 * MIN_SOURCE {
+ return false;
+ }
+ let s = &timeline.segments[segment];
+ let cut = s.start + MIN_SOURCE + at * (source_len(s) - 2.0 * MIN_SOURCE);
+ let mut tail = s.clone();
+ tail.start = cut;
+ timeline.segments[segment].end = cut;
+ timeline.segments.insert(segment + 1, tail);
+ for t in &mut timeline.transitions {
+ if t.segment_index as usize > segment {
+ t.segment_index += 1;
+ }
+ }
+ }
+ Op::Delete { segment } => {
+ if !valid(segment) || count < 2 {
+ return false;
+ }
+ timeline.segments.remove(segment);
+ let k = segment as u32;
+ timeline
+ .transitions
+ .retain(|t| t.segment_index != k && t.segment_index != k + 1);
+ for t in &mut timeline.transitions {
+ if t.segment_index > k + 1 {
+ t.segment_index -= 1;
+ }
+ }
+ }
+ Op::TrimStart { segment, by } | Op::TrimEnd { segment, by } => {
+ if !valid(segment) {
+ return false;
+ }
+ let s = &mut timeline.segments[segment];
+ let room = source_len(s) - MIN_SOURCE;
+ if room <= 0.0 {
+ return false;
+ }
+ if matches!(op, Op::TrimStart { .. }) {
+ s.start += by * room;
+ } else {
+ s.end -= by * room;
+ }
+ }
+ Op::Speed { segment, timescale } => {
+ if !valid(segment) {
+ return false;
+ }
+ timeline.segments[segment].timescale = timescale;
+ }
+ Op::Move { from, to } => {
+ if !valid(from) || !valid(to) || from == to {
+ return false;
+ }
+ let moved = timeline.segments.remove(from);
+ timeline.segments.insert(to, moved);
+ timeline.transitions.clear();
+ }
+ Op::Volume { segment, volume } => {
+ if !valid(segment) {
+ return false;
+ }
+ timeline.segments[segment].volume = Some(volume);
+ }
+ Op::Transition { segment, duration } => {
+ if segment == 0 || !valid(segment) {
+ return false;
+ }
+ timeline
+ .transitions
+ .retain(|t| t.segment_index as usize != segment);
+ timeline.transitions.push(ClipTransition {
+ segment_index: segment as u32,
+ kind: ClipTransitionType::CrossFade,
+ duration,
+ });
+ }
+ Op::Hold { at, length } => {
+ let start = at * total;
+ timeline
+ .text_segments
+ .push(fullscreen_text(start, start + length));
+ }
+ }
+ tidy_transitions(timeline);
+ true
+}
+
+pub fn fullscreen_text(start: f64, end: f64) -> TextSegment {
+ serde_json::from_value(serde_json::json!({
+ "start": start,
+ "end": end,
+ "content": "hold",
+ "layout": "fullscreen",
+ }))
+ .expect("text segment")
+}
+
+pub fn random_op(rng: &mut Rng, config: &ProjectConfiguration, mix: OpMix) -> Op {
+ let count = timeline(config).segments.len() as u64;
+ let segment = |rng: &mut Rng| rng.range(0, count - 1) as usize;
+ loop {
+ let op = match rng.range(0, 9) {
+ 0 | 1 => Op::Split {
+ segment: segment(rng),
+ at: rng.f64(),
+ },
+ 2 => Op::Delete {
+ segment: segment(rng),
+ },
+ 3 => Op::TrimStart {
+ segment: segment(rng),
+ by: rng.f64() * 0.6,
+ },
+ 4 => Op::TrimEnd {
+ segment: segment(rng),
+ by: rng.f64() * 0.6,
+ },
+ 5 => Op::Speed {
+ segment: segment(rng),
+ timescale: SPEEDS[rng.range(0, SPEEDS.len() as u64 - 1) as usize],
+ },
+ 6 => Op::Move {
+ from: segment(rng),
+ to: segment(rng),
+ },
+ 7 => Op::Volume {
+ segment: segment(rng),
+ volume: [0.0, 0.5, 1.5][rng.range(0, 2) as usize],
+ },
+ 8 if mix.transitions => Op::Transition {
+ segment: segment(rng),
+ duration: [0.02, 0.2, 0.4, 0.8, 3.0][rng.range(0, 4) as usize],
+ },
+ 9 if mix.holds => Op::Hold {
+ at: rng.f64(),
+ length: 0.2 + rng.f64() * 1.5,
+ },
+ _ => continue,
+ };
+ return op;
+ }
+}
+
+/// `count` random ops that all apply, starting from `base`.
+pub fn random_sequence(
+ rng: &mut Rng,
+ base: &ProjectConfiguration,
+ count: usize,
+ mix: OpMix,
+) -> Vec<Op> {
+ let mut config = base.clone();
+ let mut ops = Vec::new();
+ let mut attempts = 0;
+ while ops.len() < count && attempts < count * 20 {
+ attempts += 1;
+ let op = random_op(rng, &config, mix);
+ if apply(&mut config, &op) {
+ ops.push(op);
+ }
+ }
+ ops
+}
+
+pub fn replay(base: &ProjectConfiguration, ops: &[Op]) -> ProjectConfiguration {
+ let mut config = base.clone();
+ for op in ops {
+ apply(&mut config, op);
+ }
+ config
+}
+
+/// Greedy shrink: drops ops one at a time while `fails` still fails.
+pub fn shrink(ops: &[Op], fails: impl Fn(&[Op]) -> bool) -> Vec<Op> {
+ let mut current = ops.to_vec();
+ loop {
+ let mut reduced = false;
+ let mut i = 0;
+ while i < current.len() {
+ let mut candidate = current.clone();
+ candidate.remove(i);
+ if fails(&candidate) {
+ current = candidate;
+ reduced = true;
+ } else {
+ i += 1;
+ }
+ }
+ if !reduced {
+ return current;
+ }
+ }
+}
+
+/// A project whose recording clips last `durations` seconds, each on the
+/// timeline once, in order.
+pub fn base_config(durations: &[f64]) -> ProjectConfiguration {
+ let mut config = cap_verify::fixture::verification_project_config();
+ config.timeline = Some(TimelineConfiguration {
+ segments: durations
+ .iter()
+ .enumerate()
+ .map(|(i, &d)| TimelineSegment {
+ recording_clip: i as u32,
+ timescale: 1.0,
+ start: 0.0,
+ end: d,
+ name: None,
+ speed_audio_mode: None,
+ volume: None,
+ hide_cursor: None,
+ })
+ .collect(),
+ 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 = (0..durations.len())
+ .map(|i| ClipConfiguration {
+ index: i as u32,
+ offsets: Default::default(),
+ offsets_auto_calculated: true,
+ })
+ .collect();
+ config
+}
+
+/// 1 to 3 recording clips of 2 to 8 s (whole 30 fps frames).
+pub fn random_durations(rng: &mut Rng) -> Vec<f64> {
+ (0..rng.range(1, 3))
+ .map(|_| rng.range(60, 240) as f64 / 30.0)
+ .collect()
+}
+
+/// In-memory recording meta + source truth for `durations` (30 fps screen,
+/// no other tracks), so the core reference model can be built without media.
+pub fn synthetic_meta(durations: &[f64]) -> (RecordingMeta, SourceTruth) {
+ let segments = durations
+ .iter()
+ .enumerate()
+ .map(|(i, _)| MultipleSegment {
+ display: VideoMeta {
+ path: RelativePathBuf::from(format!("content/segments/segment-{i}/display.mp4")),
+ fps: 30,
+ start_time: Some(0.0),
+ device_id: None,
+ },
+ camera: None,
+ mic: None,
+ system_audio: None,
+ cursor: None,
+ keyboard: None,
+ display_notch: None,
+ })
+ .collect();
+ let meta = RecordingMeta {
+ platform: Some(Platform::default()),
+ project_path: std::env::temp_dir(),
+ pretty_name: "synthetic".into(),
+ sharing: None,
+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {
+ inner: MultipleSegments {
+ segments,
+ cursors: Default::default(),
+ status: Some(StudioRecordingStatus::Complete),
+ },
+ })),
+ upload: None,
+ };
+ let truth = SourceTruth {
+ segments: durations
+ .iter()
+ .enumerate()
+ .map(|(i, &d)| SegmentTruth {
+ screen: TrackTruth {
+ kind: StreamKind::Screen,
+ segment: i as u8,
+ frames: (0..(d * 30.0).round() as u32)
+ .map(|k| SourceFrame {
+ pts_secs: f64::from(k) / 30.0,
+ index: k,
+ })
+ .collect(),
+ },
+ camera: None,
+ })
+ .collect(),
+ };
+ (meta, truth)
+}
+
+#[derive(Clone, Debug)]
+pub struct Placed {
+ pub clip: u32,
+ pub start: f64,
+ pub end: f64,
+ pub timescale: f64,
+ pub duration: f64,
+ pub out_start: f64,
+ pub transition_in: f64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Source {
+ pub segment: usize,
+ pub time: f64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Mapping {
+ Single {
+ source: Source,
+ output_end: f64,
+ },
+ Transition {
+ outgoing: Source,
+ incoming: Source,
+ progress: f64,
+ output_end: f64,
+ },
+ Hold {
+ source: Source,
+ output_end: f64,
+ },
+}
+
+impl Mapping {
+ /// The source a single-frame consumer shows: the incoming side of a
+ /// transition.
+ pub fn shown(&self) -> Source {
+ match *self {
+ Mapping::Single { source, .. } | Mapping::Hold { source, .. } => source,
+ Mapping::Transition { incoming, .. } => incoming,
+ }
+ }
+}
+
+pub struct TimeModel {
+ pub segments: Vec<Placed>,
+ /// Merged hold windows in output time.
+ pub holds: Vec<(f64, f64)>,
+}
+
+impl TimeModel {
+ pub fn new(config: &ProjectConfiguration) -> Self {
+ let timeline = timeline(config);
+ let mut segments: Vec<Placed> = timeline
+ .segments
+ .iter()
+ .map(|s| Placed {
+ clip: s.recording_clip,
+ start: s.start,
+ end: s.end,
+ timescale: s.timescale,
+ duration: (s.end - s.start) / s.timescale,
+ out_start: 0.0,
+ transition_in: 0.0,
+ })
+ .collect();
+ for k in 1..segments.len() {
+ // The last transition listed for a boundary wins.
+ let Some(t) = timeline
+ .transitions
+ .iter()
+ .rev()
+ .find(|t| t.segment_index as usize == k)
+ else {
+ continue;
+ };
+ let max = segments[k - 1].duration.min(segments[k].duration) / 2.0;
+ if t.duration.is_finite() && t.duration > 0.0 && max >= MIN_TRANSITION {
+ segments[k].transition_in = t.duration.max(MIN_TRANSITION).min(max);
+ }
+ }
+ let mut at = 0.0;
+ for s in &mut segments {
+ at -= s.transition_in;
+ s.out_start = at;
+ at += s.duration;
+ }
+ let mut windows: Vec<(f64, f64)> = timeline
+ .text_segments
+ .iter()
+ .filter(|t| {
+ t.enabled && t.layout == cap_project::TextLayout::Fullscreen && t.end > t.start
+ })
+ .map(|t| (t.start, t.end))
+ .collect();
+ windows.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let mut holds: Vec<(f64, f64)> = Vec::new();
+ for w in windows {
+ match holds.last_mut() {
+ Some(last) if w.0 <= last.1 => last.1 = last.1.max(w.1),
+ _ => holds.push(w),
+ }
+ }
+ Self { segments, holds }
+ }
+
+ /// Output duration without holds.
+ pub fn base_duration(&self) -> f64 {
+ self.segments
+ .iter()
+ .map(|s| s.duration - s.transition_in)
+ .sum()
+ }
+
+ pub fn duration(&self) -> f64 {
+ self.base_duration() + self.holds.iter().map(|h| h.1 - h.0).sum::<f64>()
+ }
+
+ fn transition_out(&self, k: usize) -> f64 {
+ self.segments.get(k + 1).map_or(0.0, |n| n.transition_in)
+ }
+
+ /// Hold-free mapping at gapless time `e`.
+ pub fn base_map(&self, e: f64) -> Option<Mapping> {
+ for (k, s) in self.segments.iter().enumerate() {
+ let u = e - s.out_start;
+ if s.transition_in > 0.0 && u >= 0.0 && u < s.transition_in {
+ let prev = &self.segments[k - 1];
+ return Some(Mapping::Transition {
+ outgoing: Source {
+ segment: k - 1,
+ time: prev.start + (prev.duration - s.transition_in + u) * prev.timescale,
+ },
+ incoming: Source {
+ segment: k,
+ time: s.start + u * s.timescale,
+ },
+ progress: u / s.transition_in,
+ output_end: s.out_start + s.transition_in,
+ });
+ }
+ let single_end = s.out_start + s.duration - self.transition_out(k);
+ if u >= s.transition_in && e < single_end {
+ return Some(Mapping::Single {
+ source: Source {
+ segment: k,
+ time: s.start + u * s.timescale,
+ },
+ output_end: single_end,
+ });
+ }
+ }
+ None
+ }
+
+ /// Held output time before output time `o`.
+ pub fn held_before(&self, o: f64) -> f64 {
+ self.holds
+ .iter()
+ .map(|&(a, b)| (o.min(b) - a).max(0.0))
+ .sum()
+ }
+
+ /// Gapless -> output time, landing after every hold that starts at or
+ /// before the gapless point.
+ pub fn to_output(&self, e: f64) -> f64 {
+ let mut held = 0.0;
+ for &(a, b) in &self.holds {
+ if e >= a - held {
+ held += b - a;
+ }
+ }
+ e + held
+ }
+
+ /// Gapless -> output time for the end of a range: a range ending exactly
+ /// where a hold starts ends before the hold.
+ pub fn to_output_end(&self, e: f64) -> f64 {
+ let mut held = 0.0;
+ for &(a, b) in &self.holds {
+ if e > a - held {
+ held += b - a;
+ }
+ }
+ e + held
+ }
+
+ /// Output -> recording position on the concatenated source (clip `c`
+ /// starts at the sum of the earlier clips' durations), preferring the
+ /// last timeline segment that contains the gapless time, ends included.
+ pub fn output_to_source(&self, o: f64, clip_starts: &[f64]) -> Option<f64> {
+ let e = o - self.held_before(o);
+ self.segments.iter().rev().find_map(|s| {
+ let edited_end = s.out_start + s.duration;
+ (e >= s.out_start && e <= edited_end)
+ .then(|| clip_starts[s.clip as usize] + s.start + (e - s.out_start) * s.timescale)
+ })
+ }
+
+ pub fn map(&self, o: f64) -> Option<Mapping> {
+ if let Some(&(a, b)) = self.holds.iter().find(|&&(a, b)| o >= a && o < b) {
+ let source = self.base_map(a - self.held_before(a))?.shown();
+ return Some(Mapping::Hold {
+ source,
+ output_end: b,
+ });
+ }
+ let next_hold = self.holds.iter().map(|h| h.0).find(|&a| a > o);
+ let end = |e: f64| {
+ let out = self.to_output(e);
+ next_hold.map_or(out, |a| out.min(a))
+ };
+ Some(match self.base_map(o - self.held_before(o))? {
+ Mapping::Single { source, output_end } => Mapping::Single {
+ source,
+ output_end: end(output_end),
+ },
+ Mapping::Transition {
+ outgoing,
+ incoming,
+ progress,
+ output_end,
+ } => Mapping::Transition {
+ outgoing,
+ incoming,
+ progress,
+ output_end: end(output_end),
+ },
+ hold @ Mapping::Hold { .. } => hold,
+ })
+ }
+
+ /// Whether output time `o` is within `eps` of an edge where the mapping
+ /// changes (either side is then acceptable).
+ pub fn near_edge(&self, o: f64, eps: f64) -> bool {
+ if self
+ .holds
+ .iter()
+ .any(|&(a, b)| (o - a).abs() < eps || (o - b).abs() < eps)
+ {
+ return true;
+ }
+ let e = o - self.held_before(o);
+ self.segments.iter().enumerate().any(|(k, s)| {
+ [
+ s.out_start,
+ s.out_start + s.transition_in,
+ s.out_start + s.duration - self.transition_out(k),
+ s.out_start + s.duration,
+ ]
+ .iter()
+ .any(|edge| (e - edge).abs() < eps)
+ })
+ }
+}
+
+fn product_source(source: &cap_project::TimelineSource<'_>) -> Source {
+ Source {
+ segment: source.segment_index,
+ time: source.source_time,
+ }
+}
+
+/// The engine's mapping in model terms.
+pub fn product_map(timeline: &TimelineConfiguration, o: f64) -> Option<Mapping> {
+ Some(match timeline.get_frame_mapping(o)? {
+ TimelineFrameMapping::Single { source, output_end } => Mapping::Single {
+ source: product_source(&source),
+ output_end,
+ },
+ TimelineFrameMapping::Transition {
+ outgoing,
+ incoming,
+ progress,
+ output_end,
+ ..
+ } => Mapping::Transition {
+ outgoing: product_source(&outgoing),
+ incoming: product_source(&incoming),
+ progress,
+ output_end,
+ },
+ TimelineFrameMapping::Hold { source, output_end } => Mapping::Hold {
+ source: product_source(&source),
+ output_end,
+ },
+ })
+}
+
+fn close(a: f64, b: f64, tolerance: f64) -> bool {
+ (a - b).abs() <= tolerance
+}
+
+fn same_source(a: Source, b: Source, tolerance: f64) -> bool {
+ a.segment == b.segment && close(a.time, b.time, tolerance)
+}
+
+pub fn same_mapping(a: &Mapping, b: &Mapping, tolerance: f64) -> bool {
+ match (a, b) {
+ (
+ Mapping::Single {
+ source: s1,
+ output_end: e1,
+ },
+ Mapping::Single {
+ source: s2,
+ output_end: e2,
+ },
+ )
+ | (
+ Mapping::Hold {
+ source: s1,
+ output_end: e1,
+ },
+ Mapping::Hold {
+ source: s2,
+ output_end: e2,
+ },
+ ) => same_source(*s1, *s2, tolerance) && close(*e1, *e2, tolerance),
+ (
+ Mapping::Transition {
+ outgoing: o1,
+ incoming: i1,
+ progress: p1,
+ output_end: e1,
+ },
+ Mapping::Transition {
+ outgoing: o2,
+ incoming: i2,
+ progress: p2,
+ output_end: e2,
+ },
+ ) => {
+ same_source(*o1, *o2, tolerance)
+ && same_source(*i1, *i2, tolerance)
+ && close(*p1, *p2, tolerance)
+ && close(*e1, *e2, tolerance)
+ }
+ _ => false,
+ }
+}