From faea99e303ce4add90220a108f717ec5cbb3d2d5 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:55:29 +0000 Subject: [PATCH 1/7] feat: add demo director crate --- crates/director/Cargo.toml | 14 + crates/director/src/compile.rs | 777 ++++++++++++++++++++++++++ crates/director/src/geometry.rs | 133 +++++ crates/director/src/guide.rs | 38 ++ crates/director/src/heuristic.rs | 54 ++ crates/director/src/lib.rs | 30 ++ crates/director/src/plan.rs | 115 ++++ crates/director/src/signals.rs | 899 +++++++++++++++++++++++++++++++ crates/director/src/tests.rs | 366 +++++++++++++ 9 files changed, 2426 insertions(+) create mode 100644 crates/director/Cargo.toml create mode 100644 crates/director/src/compile.rs create mode 100644 crates/director/src/geometry.rs create mode 100644 crates/director/src/guide.rs create mode 100644 crates/director/src/heuristic.rs create mode 100644 crates/director/src/lib.rs create mode 100644 crates/director/src/plan.rs create mode 100644 crates/director/src/signals.rs create mode 100644 crates/director/src/tests.rs diff --git a/crates/director/Cargo.toml b/crates/director/Cargo.toml new file mode 100644 index 00000000000..017648eab49 --- /dev/null +++ b/crates/director/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "cap-director" +version = "0.1.0" +edition = "2024" + +[dependencies] +cap-project = { path = "../project" } + +serde = { workspace = true } +serde_json.workspace = true +workspace-hack = { version = "0.1", path = "../workspace-hack" } + +[lints] +workspace = true diff --git a/crates/director/src/compile.rs b/crates/director/src/compile.rs new file mode 100644 index 00000000000..f24844bed13 --- /dev/null +++ b/crates/director/src/compile.rs @@ -0,0 +1,777 @@ +use cap_project::{ + AspectRatio, AudioTrackSegment, BackgroundConfiguration, BackgroundSource, Camera3DKeyframe, + Camera3DProperties, Camera3DSegment, Camera3DTracks, Color, CornerStyle, Crop, PaddingMode, + ProjectConfiguration, ShadowConfiguration, StyleOverrides, StyleSegment, TextSegment, + TimelineConfiguration, TimelineSegment, XY, +}; +use serde::Serialize; +use serde_json::json; +use std::collections::HashSet; + +use crate::geometry::Rect; +use crate::plan::{Beat, BeatSheet, Look, Motion, Pace, Shot, Theme}; +use crate::signals::{ClipSignals, Moment, MomentKind, Signals, Span}; + +const OUTPUT_ASPECT: f64 = 16.0 / 9.0; +const SCREEN_MAX_PADDING: f64 = 0.4; +const CAMERA_FOV: f64 = 45.0; + +const WIDE_PADDING: f64 = 9.0; +const WIDE_ROUNDING: f64 = 4.5; +const ELEMENT_ROUNDING: f64 = 5.0; + +const JOIN_GAP_SECS: f64 = 0.4; +const IDLE_CUT_SECS: f64 = 0.8; +const IDLE_KEEP_HEAD: f64 = 0.25; +const IDLE_KEEP_TAIL: f64 = 0.1; +const MIN_PIECE_SECS: f64 = 0.08; +const MIN_SHOT_SECS: f64 = 1.3; +const RESULT_HOLD_SECS: f64 = 1.0; +const SPLIT_RESULT_HOLD_SECS: f64 = 1.7; +const CUT_AFTER_CLICK_SECS: f64 = 0.3; +const MIN_SPLIT_SECS: f64 = 1.6; +const MIN_PLACE_SECS: f64 = 0.9; +const SAME_PLACE_OVERLAP: f64 = 0.6; +const SMALL_FOCUS_AREA: f64 = 0.25; +const CLOSEUP_MIN_WIDTH: f64 = 0.34; +const CLOSEUP_MARGIN: f64 = 0.18; +const MAX_SHOT_SECS: f64 = 6.0; +const MAX_SPEED: f64 = 6.0; +const DEFAULT_CARD_SECS: f64 = 2.2; +const PUSH_PER_SEC: f64 = 0.014; +const OFFSCREEN_PAN: f64 = 8.0; +const DEFAULT_FONT: &str = "Helvetica Neue"; + +#[derive(Clone, Debug)] +pub struct MusicTrack { + /// Path of the audio file inside the project. + pub path: String, + pub name: String, + pub duration: f64, +} + +#[derive(Clone, Debug, Default)] +pub struct CompileOptions { + pub music: Option, + pub font_family: Option, +} + +#[derive(Serialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ShotReport { + pub beat: usize, + pub shot: &'static str, + pub start: f64, + pub end: f64, + /// Recording ranges as `[start, end, speed]`. + pub source: Vec<[f64; 3]>, + #[serde(skip_serializing_if = "Option::is_none")] + pub focus: Option, +} + +#[derive(Clone, Debug)] +pub struct Compiled { + pub config: ProjectConfiguration, + pub duration: f64, + pub shots: Vec, +} + +#[derive(Clone, Copy, Debug)] +struct Piece { + clip: u32, + start: f64, + end: f64, + speed: f64, +} + +impl Piece { + fn output_len(&self) -> f64 { + (self.end - self.start) / self.speed + } +} + +fn parse_hex(hex: &str) -> Option { + let hex = hex.trim().trim_start_matches('#'); + if hex.len() != 6 || !hex.is_ascii() { + return None; + } + let channel = |index: usize| u16::from_str_radix(&hex[index..index + 2], 16).ok(); + Some([channel(0)?, channel(2)?, channel(4)?]) +} + +fn backdrop(look: &Look) -> BackgroundSource { + let (from, to) = look + .backdrop + .as_ref() + .and_then(|[from, to]| Some((parse_hex(from)?, parse_hex(to)?))) + .unwrap_or(match look.theme { + Theme::Light => ([246, 246, 250], [214, 208, 240]), + Theme::Dark => ([34, 36, 48], [12, 13, 19]), + }); + BackgroundSource::Gradient { + from, + to, + angle: 145, + noise_intensity: None, + noise_scale: None, + animated: None, + animation_speed: None, + } +} + +fn subtract(span: Span, cuts: &[Span]) -> Vec { + let mut kept = vec![span]; + for cut in cuts { + kept = kept + .into_iter() + .flat_map(|piece| { + if cut.end <= piece.start || cut.start >= piece.end { + return vec![piece]; + } + let mut parts = Vec::new(); + if cut.start > piece.start { + parts.push(Span { + start: piece.start, + end: cut.start, + }); + } + if cut.end < piece.end { + parts.push(Span { + start: cut.end, + end: piece.end, + }); + } + parts + }) + .collect(); + } + kept +} + +fn typing_target_secs(keys: u32) -> f64 { + (0.5 + 0.045 * f64::from(keys)).clamp(0.9, 2.4) +} + +fn clip_pieces(clip: &ClipSignals, moments: &[&Moment], pace: Pace) -> Vec { + let mut spans: Vec = Vec::new(); + let mut held: Vec = Vec::new(); + for moment in moments { + let hold = if moment.result.is_some() { + SPLIT_RESULT_HOLD_SECS + } else { + RESULT_HOLD_SECS + }; + let hold_end = (moment.done + hold).min(clip.duration); + held.push(Span { + start: moment.at, + end: hold_end, + }); + let span = Span { + start: moment.start.max(0.0), + end: moment.end.max(hold_end).min(clip.duration), + }; + if span.is_empty() { + continue; + } + match spans.last_mut() { + Some(last) if span.start - last.end <= JOIN_GAP_SECS => { + last.end = last.end.max(span.end); + } + _ => spans.push(span), + } + } + + if pace != Pace::Real { + let cuts: Vec = clip + .idle + .iter() + .filter(|idle| idle.len() > IDLE_CUT_SECS) + .map(|idle| Span { + start: idle.start + IDLE_KEEP_HEAD, + end: idle.end - IDLE_KEEP_TAIL, + }) + .filter(|cut| !cut.is_empty()) + .flat_map(|cut| subtract(cut, &held)) + .filter(|cut| cut.len() > 0.2) + .collect(); + spans = spans + .into_iter() + .flat_map(|span| subtract(span, &cuts)) + .collect(); + } + + let base_speed = if pace == Pace::Fast { 2.0 } else { 1.0 }; + let mut pieces = Vec::new(); + for span in spans { + let mut cursor = span.start; + if pace != Pace::Real { + for burst in &clip.typing { + let start = (burst.start - 0.05).max(span.start); + let end = (burst.end + 0.1).min(span.end); + if end - start < 0.3 || start < cursor { + continue; + } + if start > cursor { + pieces.push(Piece { + clip: clip.clip, + start: cursor, + end: start, + speed: base_speed, + }); + } + let speed = ((end - start) / typing_target_secs(burst.keys)) + .max(base_speed) + .clamp(1.0, MAX_SPEED); + pieces.push(Piece { + clip: clip.clip, + start, + end, + speed: (speed * 100.0).round() / 100.0, + }); + cursor = end; + } + } + if span.end > cursor { + pieces.push(Piece { + clip: clip.clip, + start: cursor, + end: span.end, + speed: base_speed, + }); + } + } + pieces.retain(|piece| piece.end - piece.start >= MIN_PIECE_SECS); + + let total: f64 = pieces.iter().map(Piece::output_len).sum(); + if total > MAX_SHOT_SECS && pace != Pace::Real { + let squeeze = (total / MAX_SHOT_SECS).min(2.0); + for piece in &mut pieces { + piece.speed = (piece.speed * squeeze).min(MAX_SPEED); + } + } else if total < MIN_SHOT_SECS + && let Some(last) = pieces.last_mut() + { + let missing = (MIN_SHOT_SECS - total) * last.speed; + last.end = (last.end + missing).min(clip.duration); + } + pieces +} + +fn fill_distance() -> f64 { + let half_height = 1.0 / OUTPUT_ASPECT; + half_height / (CAMERA_FOV.to_radians() / 2.0).tan() +} + +fn linear_key(time: f64, value: f64) -> Camera3DKeyframe { + Camera3DKeyframe { + time, + value, + out_easing: Some([0.0, 0.0]), + in_easing: Some([1.0, 1.0]), + } +} + +fn camera_move(start: f64, end: f64, index: usize, shot: Shot, motion: Motion) -> Camera3DSegment { + let len = end - start; + let fill = fill_distance(); + let push = (PUSH_PER_SEC * len).clamp(0.02, 0.07); + let mut properties = Camera3DProperties { + fov: CAMERA_FOV, + zoom: fill, + ..Default::default() + }; + let mut tracks = Camera3DTracks::default(); + if motion == Motion::Cinematic && shot == Shot::Wide { + let side = if index % 2 == 0 { 1.0 } else { -1.0 }; + properties.tilt_x = 7.0; + properties.tilt_y = 11.0 * side; + properties.zoom = fill * 1.08; + tracks.tilt_y = vec![ + linear_key(0.0, 11.0 * side), + linear_key(len, (11.0 - 1.2 * len.min(4.0)) * side), + ]; + tracks.zoom = vec![ + linear_key(0.0, fill * 1.08), + linear_key(len, fill * (1.08 - push)), + ]; + } else { + tracks.zoom = vec![linear_key(0.0, fill), linear_key(len, fill * (1.0 - push))]; + } + Camera3DSegment { + start, + end, + enabled: true, + properties, + blur: Default::default(), + tracks, + transition_in: 0.0, + transition_out: 0.0, + } +} + +fn crop_of(rect: Rect, clip: &ClipSignals) -> Crop { + let even = |value: f64, limit: u32| ((value.round() as u32) & !1).min(limit & !1); + let width = even(rect.w * f64::from(clip.frame_width), clip.frame_width).max(2); + let height = even(rect.h * f64::from(clip.frame_height), clip.frame_height).max(2); + let x = even( + rect.x * f64::from(clip.frame_width), + clip.frame_width - width, + ); + let y = even( + rect.y * f64::from(clip.frame_height), + clip.frame_height - height, + ); + Crop { + position: XY::new(x, y), + size: XY::new(width, height), + } +} + +/// The padding that makes a cropped card take `fill` of the frame along the +/// axis that limits it, under proportional padding in a 16:9 frame. +fn padding_for_fill(crop: &Crop, fill: f64) -> f64 { + let (width, height) = (f64::from(crop.size.x), f64::from(crop.size.y)); + let long = width.max(height); + let limited = if width / height > OUTPUT_ASPECT { + width + } else { + height + }; + let factor = limited * (1.0 / fill - 1.0) / (2.0 * long); + (factor / SCREEN_MAX_PADDING * 100.0).clamp(0.0, 100.0) +} + +fn base_background(base: &ProjectConfiguration, look: &Look) -> BackgroundConfiguration { + let mut background = base.background.clone(); + background.source = backdrop(look); + background.blur = 0.0; + background.padding = WIDE_PADDING; + background.padding_mode = PaddingMode::Proportional; + background.rounding = WIDE_ROUNDING; + background.rounding_type = CornerStyle::Squircle; + background.crop = None; + background.display_position = None; + background.shadow = 60.0; + background.advanced_shadow = Some(match look.theme { + Theme::Light => ShadowConfiguration { + size: 30.0, + opacity: 22.0, + blur: 48.0, + }, + Theme::Dark => ShadowConfiguration { + size: 30.0, + opacity: 55.0, + blur: 48.0, + }, + }); + background +} + +fn resolve_shot(shot: Shot, moments: &[&Moment], focus: &Rect, first_clip: bool) -> Shot { + if shot != Shot::Auto { + return shot; + } + if first_clip { + return Shot::Wide; + } + let area = focus.area(); + if moments.iter().any(|moment| moment.kind == MomentKind::Type) || area <= 0.1 { + Shot::Closeup + } else if area <= 0.35 { + Shot::Element + } else { + Shot::Wide + } +} + +/// The backdrop and crop a shot needs, or `None` for a wide shot, which is +/// the project's own look. +fn shot_background( + shot: Shot, + focus: Rect, + clip: &ClipSignals, + base: &BackgroundConfiguration, +) -> Option { + let mut styled = base.clone(); + match shot { + Shot::Auto | Shot::Wide => return None, + Shot::Closeup => { + let rect = focus + .inflate(CLOSEUP_MARGIN, CLOSEUP_MARGIN) + .at_least(CLOSEUP_MIN_WIDTH, 0.0) + .with_aspect(OUTPUT_ASPECT, clip.frame_aspect()); + styled.crop = Some(crop_of(rect, clip)); + } + Shot::Fullbleed => { + let rect = focus + .at_least(0.3, 0.3) + .with_aspect(OUTPUT_ASPECT, clip.frame_aspect()); + styled.crop = Some(crop_of(rect, clip)); + styled.padding = 0.0; + styled.rounding = 0.0; + styled.shadow = 0.0; + styled.advanced_shadow = None; + styled.border = None; + } + Shot::Element => { + let rect = focus.at_least(0.3, 0.22).clamped(); + let crop = crop_of(rect, clip); + let fill = 0.6 + 0.22 * (rect.area() / 0.35).clamp(0.0, 1.0); + styled.padding = padding_for_fill(&crop, fill); + styled.rounding = ELEMENT_ROUNDING; + styled.crop = Some(crop); + } + } + Some(styled) +} + +/// A planner's framing, grown where it would leave the action out of the +/// picture: every click stays in frame, and so does what a single small +/// moment opened or changed. +fn cover_action(focus: Rect, moments: &[&Moment]) -> Rect { + let mut rect = focus; + for moment in moments { + if let Some([x, y]) = moment.point + && !rect.contains(x, y) + { + rect = rect.union(Rect::around(x, y, 0.04, 0.04)); + } + } + if let [only] = moments + && only.focus.area() < SMALL_FOCUS_AREA + { + rect = rect.union(only.focus); + } + rect.clamped() +} + +/// The moments of one beat as the places they happen in: neighbours whose +/// focus mostly overlaps share a place, and each place starts where its first +/// moment does. +fn places(moments: &[&Moment]) -> Vec<(f64, Rect)> { + let mut places: Vec<(f64, Rect)> = Vec::new(); + for moment in moments { + match places.last_mut() { + Some((_, rect)) if rect.overlap(&moment.focus) >= SAME_PLACE_OVERLAP => { + *rect = rect.union(moment.focus); + } + _ => places.push((moment.start, moment.focus)), + } + } + places +} + +fn output_time(pieces: &[Piece], start: f64, source: f64) -> f64 { + let mut time = start; + for piece in pieces { + if source < piece.start { + return time; + } + if source <= piece.end { + return time + (source - piece.start) / piece.speed; + } + time += piece.output_len(); + } + time +} + +fn shot_name(shot: Shot) -> &'static str { + match shot { + Shot::Auto | Shot::Wide => "wide", + Shot::Closeup => "closeup", + Shot::Element => "element", + Shot::Fullbleed => "fullbleed", + } +} + +fn text_segment(value: serde_json::Value) -> Result { + serde_json::from_value(value).map_err(|error| format!("Failed to build text: {error}")) +} + +pub fn compile( + base: &ProjectConfiguration, + signals: &Signals, + sheet: &BeatSheet, + options: &CompileOptions, +) -> Result { + if !sheet + .beats + .iter() + .any(|beat| matches!(beat, Beat::Clip { moments, .. } if !moments.is_empty())) + { + return Err("The beat sheet shows nothing from the recording".to_string()); + } + + let background = base_background(base, &sheet.look); + let ink = match sheet.look.theme { + Theme::Light => "#14151a", + Theme::Dark => "#ffffff", + }; + let font = options.font_family.as_deref().unwrap_or(DEFAULT_FONT); + + let mut segments: Vec = Vec::new(); + let mut styles: Vec = Vec::new(); + let mut texts: Vec = Vec::new(); + let mut cameras: Vec = Vec::new(); + let mut shots: Vec = Vec::new(); + let mut time = 0.0f64; + let mut clip_beats = 0usize; + let mut used: HashSet = HashSet::new(); + + for (index, beat) in sheet.beats.iter().enumerate() { + let start = time; + let (pieces, report_shot, focus) = match beat { + Beat::Card { + text, + subtext, + seconds, + } => { + let seconds = seconds + .filter(|seconds| seconds.is_finite()) + .unwrap_or(DEFAULT_CARD_SECS) + .clamp(1.0, 6.0); + let end = start + seconds; + let has_subtext = subtext.as_ref().is_some_and(|text| !text.trim().is_empty()); + texts.push(text_segment(json!({ + "start": start, + "end": end, + "track": 0, + "content": text, + "center": { "x": 0.5, "y": if has_subtext { 0.47 } else { 0.5 } }, + "size": { "x": 0.8, "y": 0.085 }, + "fontFamily": font, + "fontSize": 64.0, + "fontWeight": 500.0, + "color": ink, + "letterSpacing": -0.5, + "animationIn": "words", + "animationOut": if index + 1 == sheet.beats.len() { "none" } else { "fade" }, + "animationInDuration": 0.45, + "animationOutDuration": 0.2, + "layout": "fullscreen", + "layoutTransition": 0.05, + }))?); + if let Some(subtext) = subtext.as_ref().filter(|_| has_subtext) { + texts.push(text_segment(json!({ + "start": start + 0.25, + "end": end, + "track": 1, + "content": subtext, + "center": { "x": 0.5, "y": 0.57 }, + "size": { "x": 0.7, "y": 0.05 }, + "fontFamily": font, + "fontSize": 30.0, + "fontWeight": 400.0, + "color": ink, + "opacity": 0.62, + "animationIn": "fade", + "animationOut": "fade", + "animationInDuration": 0.4, + "animationOutDuration": 0.2, + }))?); + } + cameras.push(Camera3DSegment { + start, + end, + enabled: true, + properties: Camera3DProperties { + fov: CAMERA_FOV, + zoom: fill_distance(), + pan_x: OFFSCREEN_PAN, + ..Default::default() + }, + blur: Default::default(), + tracks: Camera3DTracks::default(), + transition_in: 0.0, + transition_out: 0.0, + }); + time = end; + (Vec::new(), "card", None) + } + Beat::Clip { + moments: ids, + shot, + focus, + pace, + caption, + } => { + let mut moments = ids + .iter() + .filter(|id| used.insert(**id)) + .map(|id| { + signals + .moment(*id) + .ok_or_else(|| format!("Beat {} names unknown moment {id}", index + 1)) + }) + .collect::, _>>()?; + moments.sort_by(|a, b| a.start.total_cmp(&b.start)); + let Some(first) = moments.first() else { + continue; + }; + if moments.iter().any(|moment| moment.clip != first.clip) { + return Err(format!( + "Beat {} mixes moments from different recordings", + index + 1 + )); + } + let clip = signals + .clip(first.clip) + .ok_or_else(|| format!("Beat {} names an unknown recording", index + 1))?; + let pieces = clip_pieces(clip, &moments, *pace); + if pieces.is_empty() { + return Err(format!("Beat {} has no footage", index + 1)); + } + let end = start + pieces.iter().map(Piece::output_len).sum::(); + let explicit_focus = focus.is_some_and(|rect| rect.is_valid()); + let focus = focus + .filter(Rect::is_valid) + .map(|rect| cover_action(rect, &moments)) + .unwrap_or_else(|| { + moments + .iter() + .map(|moment| moment.focus) + .reduce(Rect::union) + .unwrap_or(Rect::FULL) + }); + let shot = resolve_shot(*shot, &moments, &focus, clip_beats == 0); + clip_beats += 1; + + let split = (!explicit_focus + && moments.len() == 1 + && end - start >= MIN_SPLIT_SECS + && matches!(shot, Shot::Closeup | Shot::Element)) + .then(|| moments[0]) + .and_then(|moment| Some((moment.action?, moment.result?, moment.at))); + let framings = match split { + Some((action, result, at)) => { + let cut = output_time(&pieces, start, at + CUT_AFTER_CLICK_SECS) + .clamp(start + 0.4, end - 0.7); + vec![ + (start, cut, Shot::Closeup, action), + (cut, end, Shot::Closeup, result), + ] + } + None if !explicit_focus && matches!(shot, Shot::Closeup | Shot::Element) => { + places(&moments) + .into_iter() + .map(|(from, rect)| (output_time(&pieces, start, from), rect)) + .fold( + Vec::new(), + |mut framings: Vec<(f64, f64, Shot, Rect)>, (from, rect)| { + match framings.last_mut() { + Some(last) if from - last.0 < MIN_PLACE_SECS => { + last.3 = last.3.union(rect); + } + Some(last) => { + last.1 = from; + framings.push((from, end, shot, rect)); + } + None => framings.push((start, end, shot, rect)), + } + framings + }, + ) + } + None => vec![(start, end, shot, focus)], + }; + for (part, (from, to, shot, rect)) in framings.into_iter().enumerate() { + if let Some(styled) = shot_background(shot, rect, clip, &background) { + styles.push(StyleSegment { + start: from, + end: to, + track: 0, + enabled: true, + name: "Shot".to_string(), + overrides: StyleOverrides { + background: Some(styled), + ..Default::default() + }, + }); + } + cameras.push(camera_move(from, to, index + part, shot, sheet.look.motion)); + } + + if let Some(caption) = caption.as_ref().filter(|text| !text.trim().is_empty()) { + texts.push(text_segment(json!({ + "start": start + 0.15, + "end": end, + "track": 2, + "content": caption, + "center": { "x": 0.5, "y": 0.9 }, + "size": { "x": 0.6, "y": 0.1 }, + "fontFamily": font, + "fontSize": 30.0, + "fontWeight": 500.0, + "color": "#ffffff", + "backgroundColor": "#14151acc", + "backgroundStyle": "pill", + "animationIn": "slideUp", + "animationOut": "fade", + "animationInDuration": 0.3, + "animationOutDuration": 0.2, + }))?); + } + (pieces, shot_name(shot), Some(focus)) + } + }; + + for piece in &pieces { + segments.push(TimelineSegment { + recording_clip: piece.clip, + timescale: piece.speed, + start: piece.start, + end: piece.end, + ..Default::default() + }); + time += piece.output_len(); + } + shots.push(ShotReport { + beat: index + 1, + shot: report_shot, + start, + end: time, + source: pieces + .iter() + .map(|piece| [piece.start, piece.end, piece.speed]) + .collect(), + focus, + }); + } + + let mut timeline: TimelineConfiguration = + serde_json::from_value(json!({ "segments": [], "zoomSegments": [] })) + .map_err(|error| format!("Failed to build timeline: {error}"))?; + timeline.segments = segments; + timeline.style_segments = styles; + timeline.text_segments = texts; + timeline.camera3d_segments = cameras; + if let Some(music) = options.music.as_ref().filter(|_| sheet.look.music) { + timeline.audio_segments = vec![AudioTrackSegment { + start: 0.0, + end: time, + track: 0, + path: music.path.clone(), + name: Some(music.name.clone()), + enabled: true, + trim_start: 0.0, + volume_db: -6.0, + fade_in: 0.4, + fade_out: 1.6_f64.min(time / 3.0), + duration: Some(music.duration), + }]; + } + + let mut config = base.clone(); + config.aspect_ratio = Some(AspectRatio::Wide); + config.background = background; + config.cursor.ripple.enabled = true; + config.cursor.ripple.size = 0.6; + config.cursor.ripple.strength = 0.55; + config.timeline = Some(timeline); + + Ok(Compiled { + config, + duration: time, + shots, + }) +} diff --git a/crates/director/src/geometry.rs b/crates/director/src/geometry.rs new file mode 100644 index 00000000000..758ea060580 --- /dev/null +++ b/crates/director/src/geometry.rs @@ -0,0 +1,133 @@ +use serde::{Deserialize, Serialize}; + +/// A box in fractions of the recorded frame: `x`/`y` are the top-left corner. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] +pub struct Rect { + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, +} + +impl Rect { + pub const FULL: Rect = Rect { + x: 0.0, + y: 0.0, + w: 1.0, + h: 1.0, + }; + + pub fn new(x: f64, y: f64, w: f64, h: f64) -> Self { + Self { x, y, w, h } + } + + pub fn around(cx: f64, cy: f64, w: f64, h: f64) -> Self { + Self::new(cx - w / 2.0, cy - h / 2.0, w, h) + } + + pub fn is_valid(&self) -> bool { + [self.x, self.y, self.w, self.h] + .iter() + .all(|value| value.is_finite()) + && self.w > 0.0 + && self.h > 0.0 + } + + pub fn center(&self) -> (f64, f64) { + (self.x + self.w / 2.0, self.y + self.h / 2.0) + } + + pub fn right(&self) -> f64 { + self.x + self.w + } + + pub fn bottom(&self) -> f64 { + self.y + self.h + } + + pub fn area(&self) -> f64 { + self.w.max(0.0) * self.h.max(0.0) + } + + pub fn contains(&self, x: f64, y: f64) -> bool { + x >= self.x && x <= self.right() && y >= self.y && y <= self.bottom() + } + + pub fn union(self, other: Rect) -> Rect { + let x = self.x.min(other.x); + let y = self.y.min(other.y); + Rect::new( + x, + y, + self.right().max(other.right()) - x, + self.bottom().max(other.bottom()) - y, + ) + } + + pub fn intersection_area(&self, other: &Rect) -> f64 { + let w = self.right().min(other.right()) - self.x.max(other.x); + let h = self.bottom().min(other.bottom()) - self.y.max(other.y); + if w <= 0.0 || h <= 0.0 { 0.0 } else { w * h } + } + + /// Share of the smaller box that the two have in common. + pub fn overlap(&self, other: &Rect) -> f64 { + let smaller = self.area().min(other.area()); + if smaller <= 0.0 { + 0.0 + } else { + self.intersection_area(other) / smaller + } + } + + /// Grows each side by a fraction of the box's own size. + pub fn inflate(self, fx: f64, fy: f64) -> Rect { + Rect::new( + self.x - self.w * fx, + self.y - self.h * fy, + self.w * (1.0 + 2.0 * fx), + self.h * (1.0 + 2.0 * fy), + ) + } + + /// Grows around the center until it is at least `min_w` by `min_h`. + pub fn at_least(self, min_w: f64, min_h: f64) -> Rect { + let (cx, cy) = self.center(); + Rect::around(cx, cy, self.w.max(min_w), self.h.max(min_h)) + } + + /// Moves and, only if it has to, shrinks the box so it sits in the frame. + pub fn clamped(self) -> Rect { + let w = self.w.clamp(0.0, 1.0); + let h = self.h.clamp(0.0, 1.0); + let (cx, cy) = self.center(); + Rect::new( + (cx - w / 2.0).clamp(0.0, 1.0 - w), + (cy - h / 2.0).clamp(0.0, 1.0 - h), + w, + h, + ) + } + + /// The smallest box around this one whose pixels have `pixel_aspect` + /// (width over height) in a frame of `frame_aspect`, kept in the frame. + pub fn with_aspect(self, pixel_aspect: f64, frame_aspect: f64) -> Rect { + let target = pixel_aspect / frame_aspect; + let (mut w, mut h) = (self.w, self.h); + if w / h < target { + w = h * target; + } else { + h = w / target; + } + if w > 1.0 { + h /= w; + w = 1.0; + } + if h > 1.0 { + w /= h; + h = 1.0; + } + let (cx, cy) = self.center(); + Rect::around(cx, cy, w, h).clamped() + } +} diff --git a/crates/director/src/guide.rs b/crates/director/src/guide.rs new file mode 100644 index 00000000000..4fdb7ec54dc --- /dev/null +++ b/crates/director/src/guide.rs @@ -0,0 +1,38 @@ +/// What a planner needs to know to write a beat sheet. Shown to agents over +/// MCP; Cap's own planner carries the same rules server-side. +pub const PLANNER_GUIDE: &str = r##"You are directing a short product demo cut from a raw screen recording. + +You get the recording as numbered MOMENTS. A moment is one thing the person did (a click, a run of typing) together with the cursor moving to it and the screen settling afterwards. Each has: id, kind, start/end seconds in the recording, the typed text or clicked label when known, `focus` (the box on screen where it happened, as x/y/w/h fractions of the frame) and sometimes `containers` (bigger boxes around it, inner to outer). Frames of the moments are attached as images named by moment id; look at them. + +You answer with one JSON object, the BEAT SHEET: + +{ + "title": "Short name of what is being shown", + "look": { "theme": "light" | "dark", "backdrop": ["#f6f6fa", "#d6d0f0"], "motion": "flat" | "cinematic", "music": true }, + "beats": [ + { "type": "card", "text": "One line that sets up the demo", "subtext": "optional smaller line", "seconds": 2.0 }, + { "type": "clip", "moments": [1], "shot": "wide", "caption": null }, + { "type": "clip", "moments": [2, 3], "shot": "closeup", "focus": { "x": 0.2, "y": 0.1, "w": 0.4, "h": 0.3 } }, + { "type": "card", "text": "The payoff, in the product's own words" } + ] +} + +Shots: +- "wide": the whole window as a card on the backdrop. Use it to establish where we are and for results that fill the window. +- "closeup": zoomed into the focus, still inside the window. Use it for typing and for small controls. +- "element": only the focus box, lifted out as its own floating card. Use it for a panel, a menu, a dialog or a result that reads on its own. The box must be at least about a third of the frame wide. +- "fullbleed": the focus fills the whole frame edge to edge. Use it sparingly, for one hero moment. +- "auto": let Cap choose from the size of the focus. +When a click changes something elsewhere on screen (a toggle in a toolbar that restyles a preview), a clip of that one moment with shot "auto", "closeup" or "element" and no focus cuts from the click to its effect by itself. + +Rules: +1. Tell one story: what the product does, the few steps that show it, the result. Open with a card that says what is being shown, then the steps, then the result, then one closing card. Use "wide" only when the whole window matters; when the action is a small part of a mostly empty window, frame it with "closeup" or "element". +2. Keep only the moments that move the story. Drop mistakes, repeats, wandering and waiting. Keep the moments in the order they happened. +3. Join moments that belong to one step and happen in the same place into one clip. Give separate steps separate clips. +4. Every cut should land on a visibly different framing than the shot before it: change the shot type or the focus. +5. Set `focus` only when the moment's own focus is wrong or you want a container instead; copy numbers from `focus` or `containers`, do not invent them. Pick `theme` and `backdrop` to suit the product's own colors. +6. Cards: at most 6 words of text, no end punctuation unless it is a sentence, sentence case. One opening card at most and one closing card at most. The closing card says what the viewer can now do in a few plain words, never just the name of a button. Use each moment in one clip only. Captions are optional and at most 5 words; leave them out when the picture explains itself. +7. Aim for 15 to 30 seconds. You do not set timings: Cap cuts dead time, speeds up typing and paces the camera. "pace": "fast" speeds a step that only needs to be seen to happen; "real" keeps it exactly as recorded. + +Answer with the JSON object only. +"##; diff --git a/crates/director/src/heuristic.rs b/crates/director/src/heuristic.rs new file mode 100644 index 00000000000..fd86681c07b --- /dev/null +++ b/crates/director/src/heuristic.rs @@ -0,0 +1,54 @@ +use crate::plan::{Beat, BeatSheet, Look, Pace, Shot}; +use crate::signals::{Moment, MomentKind, Signals}; + +const SAME_PLACE_OVERLAP: f64 = 0.6; +const SAME_SHOT_GAP_SECS: f64 = 2.5; + +/// A beat sheet from the signals alone: every click and every run of typing +/// in order, moments that happen in the same place joined into one shot, and +/// everything else cut. No cards, because nothing here knows what the +/// recording is about. +pub fn plan(signals: &Signals) -> BeatSheet { + let mut groups: Vec> = Vec::new(); + for moment in signals + .moments + .iter() + .filter(|moment| matches!(moment.kind, MomentKind::Click | MomentKind::Type)) + { + let joins = groups.last().is_some_and(|group| { + let last = group[group.len() - 1]; + last.clip == moment.clip + && moment.start - last.end <= SAME_SHOT_GAP_SECS + && last.focus.overlap(&moment.focus) >= SAME_PLACE_OVERLAP + }); + if joins && let Some(group) = groups.last_mut() { + group.push(moment); + } else { + groups.push(vec![moment]); + } + } + + if groups.is_empty() { + groups = signals + .moments + .iter() + .filter(|moment| moment.kind == MomentKind::Change) + .map(|moment| vec![moment]) + .collect(); + } + + BeatSheet { + title: None, + look: Look::default(), + beats: groups + .into_iter() + .map(|group| Beat::Clip { + moments: group.iter().map(|moment| moment.id).collect(), + shot: Shot::Auto, + focus: None, + pace: Pace::Auto, + caption: None, + }) + .collect(), + } +} diff --git a/crates/director/src/lib.rs b/crates/director/src/lib.rs new file mode 100644 index 00000000000..a8358e6ef6c --- /dev/null +++ b/crates/director/src/lib.rs @@ -0,0 +1,30 @@ +//! Turns a raw recording into an edited demo. +//! +//! Three stages, each usable on its own: +//! +//! 1. [`signals`] reads what happened in the recording (clicks, typing, what +//! changed on screen and where) and groups it into numbered moments. +//! 2. A planner picks the story as a [`plan::BeatSheet`]: which moments to +//! keep, the shot for each, and any title cards. The planner is a model +//! (Cap's own or the user's agent over MCP) or [`heuristic::plan`] when +//! there is none. It never writes timings or camera numbers. +//! 3. [`compile`] turns the beat sheet into an ordinary project +//! configuration, so every decision stays editable in the editor. + +pub mod compile; +pub mod geometry; +pub mod guide; +pub mod heuristic; +pub mod plan; +pub mod signals; + +#[cfg(test)] +mod tests; + +pub use compile::{CompileOptions, Compiled, MusicTrack, ShotReport, compile}; +pub use geometry::Rect; +pub use plan::{Beat, BeatSheet, Look, Motion, Pace, Shot, Theme}; +pub use signals::{ + ElementHint, GrayFrame, Moment, MomentKind, SignalInput, Signals, Span, VisualSample, analyze, + visual_samples, +}; diff --git a/crates/director/src/plan.rs b/crates/director/src/plan.rs new file mode 100644 index 00000000000..b9fd16a97c1 --- /dev/null +++ b/crates/director/src/plan.rs @@ -0,0 +1,115 @@ +use serde::{Deserialize, Serialize}; + +use crate::geometry::Rect; + +/// The story of a demo. A planner writes this; it carries no timings and no +/// camera numbers, only what to show and how to frame it. +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BeatSheet { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default)] + pub look: Look, + pub beats: Vec, +} + +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Look { + #[serde(default)] + pub theme: Theme, + /// Two hex colors for the backdrop gradient, light to dark. Left out, the + /// theme's own backdrop is used. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub backdrop: Option<[String; 2]>, + #[serde(default)] + pub motion: Motion, + #[serde(default = "default_true")] + pub music: bool, +} + +fn default_true() -> bool { + true +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum Theme { + #[default] + Light, + Dark, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum Motion { + /// Straight on, slow push in on every shot. + #[default] + Flat, + /// Wide shots sit at a slight angle and drift. + Cinematic, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum Beat { + /// Words on the backdrop, no recording. + #[serde(rename_all = "camelCase")] + Card { + text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + subtext: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + seconds: Option, + }, + /// One or more moments of the recording, in order, as a single shot. + #[serde(rename_all = "camelCase")] + Clip { + moments: Vec, + #[serde(default)] + shot: Shot, + /// What to frame, in fractions of the recorded frame. Left out, the + /// moments' own focus is used. + #[serde(default, skip_serializing_if = "Option::is_none")] + focus: Option, + #[serde(default)] + pace: Pace, + #[serde(default, skip_serializing_if = "Option::is_none")] + caption: Option, + }, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum Shot { + /// Let the compiler choose from the size of the focus. + #[default] + Auto, + /// The whole window as a card on the backdrop. + Wide, + /// Zoomed into the focus inside the window card. + Closeup, + /// Only the focus, lifted out as its own card on the backdrop. + Element, + /// The focus filling the whole frame, edge to edge. + Fullbleed, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum Pace { + /// Dead time cut, typing sped up. + #[default] + Auto, + /// Exactly as recorded. + Real, + /// Everything sped up, for a step that only needs to be seen to happen. + Fast, +} + +impl BeatSheet { + pub fn from_json(json: &str) -> Result { + serde_json::from_str(json).map_err(|error| format!("Invalid beat sheet: {error}")) + } +} diff --git a/crates/director/src/signals.rs b/crates/director/src/signals.rs new file mode 100644 index 00000000000..a08a5c55f82 --- /dev/null +++ b/crates/director/src/signals.rs @@ -0,0 +1,899 @@ +use cap_project::{CursorEvents, KeyboardEvents}; +use serde::{Deserialize, Serialize}; + +use crate::geometry::Rect; + +pub const SIGNALS_VERSION: u32 = 1; + +const BUCKET: f64 = 0.1; +const PIXEL_DIFF: i16 = 14; +const MIN_CHANGED_PIXELS: usize = 3; +const VISUAL_ACTIVE: f32 = 0.0004; +const CURSOR_ACTIVE: f64 = 0.003; +const DOUBLE_CLICK_SECS: f64 = 0.35; +const TYPING_GAP_SECS: f64 = 1.2; +const CLICK_THEN_TYPE_SECS: f64 = 2.0; +const MAX_LEAD_SECS: f64 = 1.4; +const MIN_TAIL_SECS: f64 = 0.7; +const MAX_TAIL_SECS: f64 = 3.5; +const MIN_IDLE_SECS: f64 = 0.5; +const MIN_PASSIVE_SECS: f64 = 0.8; + +const MODIFIER_KEYS: &[&str] = &[ + "Shift", "LShift", "RShift", "Control", "LControl", "RControl", "Alt", "LAlt", "RAlt", + "Option", "LOption", "ROption", "LMeta", "RMeta", "Meta", "Command", "RCommand", "CapsLock", + "Fn", +]; +const COMMAND_KEYS: &[&str] = &[ + "Control", "LControl", "RControl", "LMeta", "RMeta", "Meta", "Command", "RCommand", +]; +const SHIFT_KEYS: &[&str] = &["Shift", "LShift", "RShift"]; +const SHIFTED: &[(char, char)] = &[ + ('1', '!'), + ('2', '@'), + ('3', '#'), + ('4', '$'), + ('5', '%'), + ('6', '^'), + ('7', '&'), + ('8', '*'), + ('9', '('), + ('0', ')'), + ('-', '_'), + ('=', '+'), + ('[', '{'), + (']', '}'), + ('\\', '|'), + (';', ':'), + ('\'', '"'), + (',', '<'), + ('.', '>'), + ('/', '?'), + ('`', '~'), +]; +const LARGE_CHANGE_AREA: f64 = 0.3; +pub const MASK_COLS: usize = 32; +pub const MASK_ROWS: usize = 20; +const MASK_CELL_PIXELS: u16 = 2; +const RESULT_MIN_CELLS: usize = 3; +const RESULT_MIN_DISTANCE: f64 = 0.16; + +fn shifted(character: char) -> char { + SHIFTED + .iter() + .find(|(plain, _)| *plain == character) + .map_or_else(|| character.to_ascii_uppercase(), |(_, shifted)| *shifted) +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] +pub struct Span { + pub start: f64, + pub end: f64, +} + +impl Span { + pub fn len(&self) -> f64 { + (self.end - self.start).max(0.0) + } + + pub fn is_empty(&self) -> bool { + self.end <= self.start + } +} + +/// One small grayscale frame of the screen track, in recording time. +pub struct GrayFrame { + pub t: f64, + pub width: usize, + pub height: usize, + pub data: Vec, +} + +/// How much of the screen changed since the previous sample, and where. +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct VisualSample { + pub t: f64, + pub amount: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rect: Option, + /// Which cells of a `MASK_COLS` by `MASK_ROWS` grid changed, one row of + /// bits per entry. Empty when nothing did. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub mask: Vec, +} + +pub fn visual_samples(frames: &[GrayFrame]) -> Vec { + frames + .windows(2) + .filter(|pair| { + pair[0].width == pair[1].width + && pair[0].height == pair[1].height + && pair[0].data.len() == pair[1].data.len() + && pair[0].width > 0 + && pair[0].height > 0 + }) + .map(|pair| { + let (before, after) = (&pair[0], &pair[1]); + let (width, height) = (after.width, after.height); + let mut count = 0usize; + let mut cells = [0u16; MASK_COLS * MASK_ROWS]; + let (mut min_x, mut min_y, mut max_x, mut max_y) = (width, height, 0usize, 0usize); + for (index, (a, b)) in before.data.iter().zip(&after.data).enumerate() { + if (i16::from(*a) - i16::from(*b)).abs() <= PIXEL_DIFF { + continue; + } + count += 1; + let (x, y) = (index % width, index / width); + let cell = (y * MASK_ROWS / height) * MASK_COLS + x * MASK_COLS / width; + cells[cell] = cells[cell].saturating_add(1); + min_x = min_x.min(x); + max_x = max_x.max(x); + min_y = min_y.min(y); + max_y = max_y.max(y); + } + let rect = (count >= MIN_CHANGED_PIXELS).then(|| { + Rect::new( + min_x as f64 / width as f64, + min_y as f64 / height as f64, + (max_x + 1 - min_x) as f64 / width as f64, + (max_y + 1 - min_y) as f64 / height as f64, + ) + }); + VisualSample { + t: after.t, + amount: if rect.is_some() { + count as f32 / (width * height) as f32 + } else { + 0.0 + }, + mask: if rect.is_some() { + cells + .chunks(MASK_COLS) + .map(|row| { + row.iter().enumerate().fold(0u32, |bits, (col, hits)| { + if *hits >= MASK_CELL_PIXELS { + bits | 1 << col + } else { + bits + } + }) + }) + .collect() + } else { + Vec::new() + }, + rect, + } + }) + .collect() +} + +/// Where an action landed, from the page or the accessibility tree, when the +/// capture recorded it. Optional: without hints the focus comes from what +/// changed on screen around the action. +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ElementHint { + pub t: f64, + #[serde(default)] + pub t_end: Option, + #[serde(default)] + pub kind: Option, + #[serde(default)] + pub label: Option, + #[serde(default)] + pub role: Option, + #[serde(default)] + pub text: Option, + pub rect: Rect, + #[serde(default)] + pub containers: Vec, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct HintContainer { + #[serde(flatten)] + pub rect: Rect, + #[serde(default)] + pub hint: Option, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug)] +pub struct Click { + pub t: f64, + pub x: f64, + pub y: f64, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct Typing { + pub start: f64, + pub end: f64, + pub text: String, + pub keys: u32, +} + +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum MomentKind { + Click, + Type, + Change, + Wander, +} + +/// One thing that happened: the approach, the action and the screen settling +/// after it. Times are seconds in the recording. +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Moment { + pub id: u32, + pub clip: u32, + pub kind: MomentKind, + pub start: f64, + pub end: f64, + /// When the action starts (the click, the first key) and when it is over + /// (the same click, the last key). + pub at: f64, + pub done: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub point: Option<[f64; 2]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + pub focus: Rect, + /// Where the action itself landed, and where on screen its effect showed + /// when that was somewhere else (a toggle in a toolbar changing a preview). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub action: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub changed: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub containers: Vec, + pub weight: f32, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct ClipSignals { + pub clip: u32, + pub duration: f64, + pub frame_width: u32, + pub frame_height: u32, + pub clicks: Vec, + pub typing: Vec, + pub idle: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub visual: Vec, +} + +impl ClipSignals { + pub fn frame_aspect(&self) -> f64 { + f64::from(self.frame_width.max(1)) / f64::from(self.frame_height.max(1)) + } +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Signals { + pub version: u32, + pub clips: Vec, + pub moments: Vec, +} + +impl Signals { + pub fn moment(&self, id: u32) -> Option<&Moment> { + self.moments.iter().find(|moment| moment.id == id) + } + + pub fn clip(&self, clip: u32) -> Option<&ClipSignals> { + self.clips.iter().find(|signals| signals.clip == clip) + } + + /// The same signals without the per-sample screen track, which a planner + /// has no use for and which dwarfs everything else. + pub fn brief(&self) -> Signals { + let mut brief = self.clone(); + for clip in &mut brief.clips { + clip.visual.clear(); + } + brief + } +} + +pub struct SignalInput<'a> { + pub clip: u32, + pub duration: f64, + pub frame_width: u32, + pub frame_height: u32, + pub cursor: &'a CursorEvents, + pub keyboard: &'a KeyboardEvents, + pub visual: &'a [VisualSample], + pub elements: &'a [ElementHint], +} + +pub fn analyze(inputs: &[SignalInput<'_>]) -> Signals { + let mut clips = Vec::new(); + let mut moments = Vec::new(); + for input in inputs { + let (clip, mut clip_moments) = analyze_clip(input); + clips.push(clip); + moments.append(&mut clip_moments); + } + for (index, moment) in moments.iter_mut().enumerate() { + moment.id = index as u32 + 1; + } + Signals { + version: SIGNALS_VERSION, + clips, + moments, + } +} + +fn cursor_at(cursor: &CursorEvents, time_ms: f64) -> Option<(f64, f64)> { + let index = cursor + .moves + .partition_point(|event| event.time_ms <= time_ms); + let event = if index == 0 { + cursor.moves.first()? + } else { + &cursor.moves[index - 1] + }; + (event.x.is_finite() && event.y.is_finite()) + .then(|| (event.x.clamp(0.0, 1.0), event.y.clamp(0.0, 1.0))) +} + +fn clicks(cursor: &CursorEvents, duration: f64) -> Vec { + let mut clicks: Vec = Vec::new(); + for event in cursor.clicks.iter().filter(|event| event.down) { + let t = event.time_ms / 1000.0; + if !t.is_finite() || t < 0.0 || t > duration { + continue; + } + if clicks + .last() + .is_some_and(|last| t - last.t < DOUBLE_CLICK_SECS) + { + continue; + } + let Some((x, y)) = cursor_at(cursor, event.time_ms) else { + continue; + }; + clicks.push(Click { t, x, y }); + } + clicks +} + +fn typing(keyboard: &KeyboardEvents, duration: f64) -> Vec { + let mut bursts: Vec = Vec::new(); + let mut commands: Vec<&str> = Vec::new(); + let mut shifts: Vec<&str> = Vec::new(); + let mut current: Option = None; + for event in &keyboard.presses { + let key = event.key.as_str(); + if SHIFT_KEYS.contains(&key) { + if event.down { + shifts.push(key); + } else { + shifts.retain(|held| *held != key); + } + continue; + } + if COMMAND_KEYS.contains(&key) { + if event.down { + commands.push(key); + } else { + commands.retain(|held| *held != key); + } + continue; + } + let t = event.time_ms / 1000.0; + if !event.down || MODIFIER_KEYS.contains(&key) || !t.is_finite() || t < 0.0 || t > duration + { + continue; + } + if !commands.is_empty() { + continue; + } + let typed = match key { + "Space" => Some(' '), + "Enter" | "Return" => Some('\n'), + "Tab" => Some('\t'), + "Backspace" | "Delete" => None, + _ => { + let mut chars = key.chars(); + match (chars.next(), chars.next()) { + (Some(only), None) if shifts.is_empty() => Some(only), + (Some(only), None) => Some(shifted(only)), + _ => continue, + } + } + }; + if current + .as_ref() + .is_some_and(|burst| t - burst.end > TYPING_GAP_SECS) + && let Some(done) = current.take() + { + bursts.push(done); + } + let burst = current.get_or_insert_with(|| Typing { + start: t, + end: t, + text: String::new(), + keys: 0, + }); + burst.end = t; + burst.keys += 1; + match typed { + Some(character) => burst.text.push(character), + None => { + burst.text.pop(); + } + } + } + bursts.extend(current); + bursts.retain(|burst| burst.keys >= 2); + bursts +} + +struct Activity { + cursor: Vec, + keys: Vec, + visual: Vec, +} + +impl Activity { + fn len(&self) -> usize { + self.cursor.len() + } + + fn any(&self, bucket: usize) -> bool { + self.cursor[bucket] || self.keys[bucket] || self.visual[bucket] + } +} + +fn bucket_of(t: f64, buckets: usize) -> usize { + ((t / BUCKET).floor().max(0.0) as usize).min(buckets.saturating_sub(1)) +} + +fn activity(input: &SignalInput<'_>) -> Activity { + let buckets = ((input.duration / BUCKET).ceil() as usize).max(1); + let mut cursor = vec![false; buckets]; + let mut keys = vec![false; buckets]; + let mut visual = vec![false; buckets]; + let mut travelled = vec![0.0f64; buckets]; + for pair in input.cursor.moves.windows(2) { + let t = pair[1].time_ms / 1000.0; + if !t.is_finite() || t < 0.0 || t > input.duration { + continue; + } + let distance = ((pair[1].x - pair[0].x).powi(2) + (pair[1].y - pair[0].y).powi(2)).sqrt(); + if distance.is_finite() { + travelled[bucket_of(t, buckets)] += distance; + } + } + for (bucket, distance) in travelled.iter().enumerate() { + cursor[bucket] = *distance > CURSOR_ACTIVE; + } + for event in input.keyboard.presses.iter().filter(|event| event.down) { + let t = event.time_ms / 1000.0; + if t.is_finite() && t >= 0.0 && t <= input.duration { + keys[bucket_of(t, buckets)] = true; + } + } + for sample in input.visual { + if sample.amount > VISUAL_ACTIVE && sample.t >= 0.0 && sample.t <= input.duration { + visual[bucket_of(sample.t, buckets)] = true; + } + } + Activity { + cursor, + keys, + visual, + } +} + +enum Action { + Click(Click), + Type { + typing: Typing, + click: Option, + }, +} + +impl Action { + fn at(&self) -> f64 { + match self { + Action::Click(click) => click.t, + Action::Type { typing, click } => click.map_or(typing.start, |click| click.t), + } + } + + fn done(&self) -> f64 { + match self { + Action::Click(click) => click.t, + Action::Type { typing, .. } => typing.end, + } + } +} + +fn actions(clicks: &[Click], typing: &[Typing]) -> Vec { + let mut used = vec![false; clicks.len()]; + let mut actions = Vec::new(); + for burst in typing { + let click = clicks + .iter() + .enumerate() + .rev() + .find(|(_, click)| click.t <= burst.start) + .filter(|(_, click)| burst.start - click.t <= CLICK_THEN_TYPE_SECS) + .map(|(index, click)| { + used[index] = true; + *click + }); + actions.push(Action::Type { + typing: burst.clone(), + click, + }); + } + for (index, click) in clicks.iter().enumerate() { + let inside_typing = typing + .iter() + .any(|burst| click.t > burst.start && click.t < burst.end); + if !used[index] && !inside_typing { + actions.push(Action::Click(*click)); + } + } + actions.sort_by(|a, b| a.at().total_cmp(&b.at())); + actions +} + +fn walk_back(flags: &[bool], from: f64, floor: f64, gap: f64) -> f64 { + let mut start = from; + let mut quiet = 0.0; + let mut bucket = bucket_of(from, flags.len()); + loop { + let bucket_start = bucket as f64 * BUCKET; + if bucket_start < floor || from - bucket_start > MAX_LEAD_SECS { + break; + } + if flags[bucket] { + start = bucket_start; + quiet = 0.0; + } else { + quiet += BUCKET; + if quiet > gap { + break; + } + } + if bucket == 0 { + break; + } + bucket -= 1; + } + start.max(floor) +} + +fn walk_forward(flags: &[bool], from: f64, ceiling: f64, gap: f64) -> f64 { + let mut end = from; + let mut quiet = 0.0; + let mut bucket = bucket_of(from, flags.len()); + while bucket < flags.len() { + let bucket_end = (bucket + 1) as f64 * BUCKET; + if bucket_end > ceiling || bucket_end - from > MAX_TAIL_SECS { + break; + } + if flags[bucket] { + end = bucket_end; + quiet = 0.0; + } else { + quiet += BUCKET; + if quiet > gap { + break; + } + } + bucket += 1; + } + end.min(ceiling) +} + +fn changed_between(visual: &[VisualSample], start: f64, end: f64) -> Option { + visual + .iter() + .filter(|sample| sample.t >= start && sample.t <= end && sample.amount > VISUAL_ACTIVE) + .filter_map(|sample| sample.rect) + .reduce(Rect::union) +} + +/// The largest patch of changed screen that is not where the action landed. +fn result_between( + visual: &[VisualSample], + start: f64, + end: f64, + point: (f64, f64), +) -> Option { + let mut mask = [0u32; MASK_ROWS]; + for sample in visual + .iter() + .filter(|sample| sample.t >= start && sample.t <= end && sample.mask.len() == MASK_ROWS) + { + for (row, bits) in mask.iter_mut().zip(&sample.mask) { + *row |= bits; + } + } + let set = |mask: &[u32; MASK_ROWS], col: usize, row: usize| mask[row] & (1 << col) != 0; + let mut seen = [0u32; MASK_ROWS]; + let mut best: Option<(usize, Rect)> = None; + for row in 0..MASK_ROWS { + for col in 0..MASK_COLS { + if !set(&mask, col, row) || set(&seen, col, row) { + continue; + } + let mut stack = vec![(col, row)]; + seen[row] |= 1 << col; + let (mut min_c, mut max_c, mut min_r, mut max_r, mut cells) = (col, col, row, row, 0); + while let Some((c, r)) = stack.pop() { + cells += 1; + min_c = min_c.min(c); + max_c = max_c.max(c); + min_r = min_r.min(r); + max_r = max_r.max(r); + for (dc, dr) in [ + (-1i32, 0i32), + (1, 0), + (0, -1), + (0, 1), + (-1, -1), + (1, 1), + (-1, 1), + (1, -1), + ] { + let (nc, nr) = (c as i32 + dc, r as i32 + dr); + if nc < 0 || nr < 0 || nc >= MASK_COLS as i32 || nr >= MASK_ROWS as i32 { + continue; + } + let (nc, nr) = (nc as usize, nr as usize); + if set(&mask, nc, nr) && !set(&seen, nc, nr) { + seen[nr] |= 1 << nc; + stack.push((nc, nr)); + } + } + } + let rect = Rect::new( + min_c as f64 / MASK_COLS as f64, + min_r as f64 / MASK_ROWS as f64, + (max_c + 1 - min_c) as f64 / MASK_COLS as f64, + (max_r + 1 - min_r) as f64 / MASK_ROWS as f64, + ); + let dx = (point.0 - point.0.clamp(rect.x, rect.right())).abs(); + let dy = (point.1 - point.1.clamp(rect.y, rect.bottom())).abs(); + if cells < RESULT_MIN_CELLS || dx.max(dy) < RESULT_MIN_DISTANCE { + continue; + } + if best.as_ref().is_none_or(|(most, _)| cells > *most) { + best = Some((cells, rect)); + } + } + } + best.map(|(_, rect)| rect) +} + +fn hint_for(elements: &[ElementHint], at: f64, done: f64) -> Option<&ElementHint> { + elements + .iter() + .filter(|hint| hint.rect.is_valid()) + .filter(|hint| hint.kind.as_deref() != Some("hover")) + .filter(|hint| hint.t <= done + 0.4 && hint.t_end.unwrap_or(hint.t) >= at - 0.4) + .min_by(|a, b| (a.t - at).abs().total_cmp(&(b.t - at).abs())) +} + +fn focus_for( + point: Option<(f64, f64)>, + changed: Option, + hint: Option<&ElementHint>, + frame_aspect: f64, +) -> Rect { + let mut focus: Option = None; + let mut add = |rect: Rect| { + focus = Some(focus.map_or(rect, |current| current.union(rect))); + }; + if let Some((x, y)) = point { + add(Rect::around(x, y, 0.06, 0.06 * frame_aspect)); + } + if let Some(hint) = hint { + add(hint.rect); + } + if let Some(changed) = changed + .filter(|rect| rect.area() < LARGE_CHANGE_AREA || (hint.is_none() && point.is_none())) + { + add(changed); + } + focus + .unwrap_or(Rect::FULL) + .inflate(0.12, 0.12) + .at_least(0.2, 0.2) + .clamped() +} + +/// Runs of `true` as `(first, one past the last)`. +fn runs(flags: impl Iterator) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut open: Option = None; + let mut len = 0; + for (index, flag) in flags.enumerate() { + len = index + 1; + match (flag, open) { + (true, None) => open = Some(index), + (false, Some(first)) => { + runs.push((first, index)); + open = None; + } + _ => {} + } + } + if let Some(first) = open { + runs.push((first, len)); + } + runs +} + +fn analyze_clip(input: &SignalInput<'_>) -> (ClipSignals, Vec) { + let duration = input.duration.max(0.0); + let clicks = clicks(input.cursor, duration); + let typing = typing(input.keyboard, duration); + let activity = activity(input); + let buckets = activity.len(); + let frame_aspect = f64::from(input.frame_width.max(1)) / f64::from(input.frame_height.max(1)); + let actions = actions(&clicks, &typing); + + let mut leads = Vec::with_capacity(actions.len()); + for (index, action) in actions.iter().enumerate() { + let floor = if index == 0 { + 0.0 + } else { + actions[index - 1].done() + 0.15 + }; + let floor = floor.min(action.at()); + let lead = walk_back(&activity.cursor, action.at(), floor, 0.3); + leads.push(lead.min((action.at() - 0.25).max(floor))); + } + + let mut moments = Vec::new(); + let mut covered = vec![false; buckets]; + for (index, action) in actions.iter().enumerate() { + let ceiling = leads.get(index + 1).copied().unwrap_or(duration); + let done = action.done(); + let settled = walk_forward(&activity.visual, done, ceiling, 0.5); + let end = settled + .max((done + MIN_TAIL_SECS).min(ceiling)) + .max(done) + .min(duration); + let start = leads[index]; + let changed = changed_between(input.visual, action.at(), end); + let (kind, point, text) = match action { + Action::Click(click) => (MomentKind::Click, Some((click.x, click.y)), None), + Action::Type { typing, click } => ( + MomentKind::Type, + click.map(|click| (click.x, click.y)), + Some(typing.text.clone()), + ), + }; + let hint = hint_for(input.elements, action.at(), done); + let changed_local = changed.filter(|rect| rect.area() < 0.6); + let focus = focus_for(point, changed_local, hint, frame_aspect); + let result = match (action, point) { + (Action::Click(_), Some(point)) => { + result_between(input.visual, action.at(), end, point) + } + _ => None, + }; + let landed = result.and(point).map(|point| { + let own = hint.map_or(Rect::around(point.0, point.1, 0.0, 0.0), |hint| hint.rect); + own.union(Rect::around(point.0, point.1, 0.06, 0.06 * frame_aspect)) + .inflate(0.12, 0.12) + .clamped() + }); + for flag in covered + .iter_mut() + .take(bucket_of(end, buckets) + 1) + .skip(bucket_of(start, buckets)) + { + *flag = true; + } + moments.push(Moment { + id: 0, + clip: input.clip, + kind, + start, + end, + at: action.at(), + done, + point: point.map(|(x, y)| [x, y]), + text, + label: hint.and_then(|hint| hint.label.clone()), + focus, + action: landed, + result: result.map(|rect| rect.inflate(0.06, 0.06).clamped()), + changed, + containers: hint + .map(|hint| { + hint.containers + .iter() + .map(|container| container.rect.clamped()) + .filter(Rect::is_valid) + .collect() + }) + .unwrap_or_default(), + weight: 1.0, + }); + } + + let passive = runs( + covered + .iter() + .enumerate() + .map(|(bucket, covered)| activity.any(bucket) && !covered), + ); + for (first, after) in passive { + let start = first as f64 * BUCKET; + let end = (after as f64 * BUCKET).min(duration); + if end - start < MIN_PASSIVE_SECS { + continue; + } + let changed = changed_between(input.visual, start, end); + let visual = activity.visual[first..after].iter().any(|flag| *flag); + moments.push(Moment { + id: 0, + clip: input.clip, + kind: if visual { + MomentKind::Change + } else { + MomentKind::Wander + }, + start, + end, + at: start, + done: start, + point: None, + text: None, + label: None, + focus: changed + .filter(|rect| rect.area() < 0.6) + .map_or(Rect::FULL, |rect| { + rect.inflate(0.12, 0.12).at_least(0.2, 0.2).clamped() + }), + action: None, + result: None, + changed, + containers: Vec::new(), + weight: if visual { 0.5 } else { 0.1 }, + }); + } + moments.sort_by(|a, b| a.start.total_cmp(&b.start)); + + let idle: Vec = runs((0..buckets).map(|bucket| !activity.any(bucket))) + .into_iter() + .map(|(first, after)| Span { + start: first as f64 * BUCKET, + end: (after as f64 * BUCKET).min(duration), + }) + .filter(|span| span.len() >= MIN_IDLE_SECS) + .collect(); + + ( + ClipSignals { + clip: input.clip, + duration, + frame_width: input.frame_width, + frame_height: input.frame_height, + clicks, + typing, + idle, + visual: input.visual.to_vec(), + }, + moments, + ) +} diff --git a/crates/director/src/tests.rs b/crates/director/src/tests.rs new file mode 100644 index 00000000000..ae7b3e5a53d --- /dev/null +++ b/crates/director/src/tests.rs @@ -0,0 +1,366 @@ +use cap_project::{ + CursorClickEvent, CursorEvents, CursorMoveEvent, KeyPressEvent, KeyboardEvents, + ProjectConfiguration, +}; + +use crate::compile::{CompileOptions, compile}; +use crate::geometry::Rect; +use crate::plan::{Beat, BeatSheet, Look, Pace, Shot}; +use crate::signals::{ + GrayFrame, MomentKind, SignalInput, Signals, VisualSample, analyze, visual_samples, +}; + +fn moves(points: &[(f64, f64, f64)]) -> Vec { + points + .iter() + .map(|(t, x, y)| CursorMoveEvent { + active_modifiers: Vec::new(), + cursor_id: "0".to_string(), + time_ms: t * 1000.0, + x: *x, + y: *y, + }) + .collect() +} + +fn click(t: f64) -> [CursorClickEvent; 2] { + let event = |time: f64, down: bool| CursorClickEvent { + active_modifiers: Vec::new(), + cursor_num: 0, + cursor_id: "0".to_string(), + time_ms: time * 1000.0, + down, + }; + [event(t, true), event(t + 0.08, false)] +} + +fn keys(start: f64, text: &str, step: f64) -> Vec { + text.chars() + .enumerate() + .flat_map(|(index, character)| { + let t = start + index as f64 * step; + let key = if character == ' ' { + "Space".to_string() + } else { + character.to_string() + }; + [ + KeyPressEvent { + key: key.clone(), + key_code: key.clone(), + time_ms: t * 1000.0, + down: true, + }, + KeyPressEvent { + key: key.clone(), + key_code: key, + time_ms: (t + 0.04) * 1000.0, + down: false, + }, + ] + }) + .collect() +} + +fn change(t: f64, rect: Rect) -> VisualSample { + VisualSample { + t, + amount: (rect.area() as f32).max(0.001), + rect: Some(rect), + mask: Vec::new(), + } +} + +fn sample_signals() -> Signals { + let mut path = Vec::new(); + for step in 0..=10 { + let t = 2.0 + f64::from(step) * 0.08; + path.push(( + t, + 0.1 + f64::from(step) * 0.03, + 0.1 + f64::from(step) * 0.02, + )); + } + for step in 0..=10 { + let t = 12.0 + f64::from(step) * 0.08; + path.push(( + t, + 0.4 + f64::from(step) * 0.03, + 0.3 + f64::from(step) * 0.04, + )); + } + let cursor = CursorEvents { + moves: moves(&path), + clicks: [click(2.9), click(12.9)].concat(), + }; + let keyboard = KeyboardEvents { + presses: keys(3.4, "hello world", 0.1), + }; + let mut visual = Vec::new(); + for step in 0..12 { + visual.push(change( + 3.4 + f64::from(step) * 0.1, + Rect::new(0.35, 0.28, 0.2, 0.05), + )); + } + for step in 0..6 { + visual.push(change( + 13.0 + f64::from(step) * 0.1, + Rect::new(0.6, 0.5, 0.25, 0.3), + )); + } + analyze(&[SignalInput { + clip: 0, + duration: 20.0, + frame_width: 3200, + frame_height: 2000, + cursor: &cursor, + keyboard: &keyboard, + visual: &visual, + elements: &[], + }]) +} + +#[test] +fn visual_samples_report_where_the_screen_changed() { + let blank = GrayFrame { + t: 0.0, + width: 10, + height: 10, + data: vec![0; 100], + }; + let mut data = vec![0; 100]; + for y in 2..5 { + for x in 6..9 { + data[y * 10 + x] = 200; + } + } + let changed = GrayFrame { + t: 0.1, + width: 10, + height: 10, + data, + }; + let samples = visual_samples(&[blank, changed]); + assert_eq!(samples.len(), 1); + let rect = samples[0].rect.expect("a changed box"); + assert!((rect.x - 0.6).abs() < 1e-9 && (rect.y - 0.2).abs() < 1e-9); + assert!((rect.w - 0.3).abs() < 1e-9 && (rect.h - 0.3).abs() < 1e-9); + assert!((samples[0].amount - 0.09).abs() < 1e-6); +} + +#[test] +fn a_click_followed_by_typing_is_one_moment() { + let signals = sample_signals(); + let actions: Vec<_> = signals + .moments + .iter() + .filter(|moment| matches!(moment.kind, MomentKind::Click | MomentKind::Type)) + .collect(); + assert_eq!(actions.len(), 2, "{:#?}", signals.moments); + assert_eq!(actions[0].kind, MomentKind::Type); + assert_eq!(actions[0].text.as_deref(), Some("hello world")); + assert!(actions[0].start < 2.9 && actions[0].start >= 2.0); + assert!(actions[0].end >= 4.4 && actions[0].end < 12.0); + assert_eq!(actions[1].kind, MomentKind::Click); + assert!(actions[1].focus.contains(0.7, 0.7)); +} + +#[test] +fn dead_time_between_actions_is_idle() { + let signals = sample_signals(); + let idle = &signals.clips[0].idle; + assert!( + idle.iter().any(|span| span.start < 6.0 && span.end > 11.0), + "{idle:?}" + ); +} + +#[test] +fn compiling_cuts_dead_time_and_speeds_typing() { + let signals = sample_signals(); + let ids: Vec = signals + .moments + .iter() + .filter(|moment| matches!(moment.kind, MomentKind::Click | MomentKind::Type)) + .map(|moment| moment.id) + .collect(); + let sheet = BeatSheet { + title: None, + look: Look::default(), + beats: vec![ + Beat::Card { + text: "Say hello".to_string(), + subtext: None, + seconds: Some(2.0), + }, + Beat::Clip { + moments: vec![ids[0]], + shot: Shot::Closeup, + focus: None, + pace: Pace::Auto, + caption: None, + }, + Beat::Clip { + moments: vec![ids[1]], + shot: Shot::Element, + focus: None, + pace: Pace::Auto, + caption: None, + }, + ], + }; + let compiled = compile( + &ProjectConfiguration::default(), + &signals, + &sheet, + &CompileOptions::default(), + ) + .expect("compiles"); + let timeline = compiled.config.timeline.expect("timeline"); + assert!(compiled.duration < 9.0, "{}", compiled.duration); + assert!( + timeline + .segments + .iter() + .any(|segment| segment.timescale > 1.0) + ); + assert!( + (timeline.duration() - compiled.duration).abs() < 1e-6, + "{} vs {}", + timeline.duration(), + compiled.duration + ); + assert!(timeline.zoom_segments.is_empty()); + assert_eq!(timeline.style_segments.len(), 2); + assert_eq!(timeline.text_segments.len(), 1); + assert_eq!(timeline.hold_windows(), vec![(0.0, 2.0)]); + assert_eq!(timeline.camera3d_segments.len(), 3); + let total: f64 = timeline + .segments + .iter() + .map(|segment| (segment.end - segment.start) / segment.timescale) + .sum(); + assert!((total + 2.0 - compiled.duration).abs() < 1e-6); + let style = &timeline.style_segments[1]; + assert!((style.start - compiled.shots[2].start).abs() < 1e-9); + let crop = style + .overrides + .background + .as_ref() + .and_then(|background| background.crop.as_ref()) + .expect("element shots crop"); + assert!(crop.size.x >= 960 && crop.position.x + crop.size.x <= 3200); + assert!(crop.size.y % 2 == 0 && crop.position.y + crop.size.y <= 2000); +} + +#[test] +fn unknown_moments_are_refused() { + let signals = sample_signals(); + let sheet = BeatSheet { + title: None, + look: Look::default(), + beats: vec![Beat::Clip { + moments: vec![99], + shot: Shot::Auto, + focus: None, + pace: Pace::Auto, + caption: None, + }], + }; + let error = compile( + &ProjectConfiguration::default(), + &signals, + &sheet, + &CompileOptions::default(), + ) + .expect_err("unknown moment"); + assert!(error.contains("99")); +} + +#[test] +fn the_heuristic_plan_keeps_actions_in_order() { + let signals = sample_signals(); + let sheet = crate::heuristic::plan(&signals); + assert_eq!(sheet.beats.len(), 2); + let compiled = compile( + &ProjectConfiguration::default(), + &signals, + &sheet, + &CompileOptions::default(), + ) + .expect("compiles"); + assert_eq!(compiled.shots[0].shot, "wide"); + assert!( + compiled + .shots + .windows(2) + .all(|pair| pair[0].end <= pair[1].start + 1e-9) + ); +} + +#[test] +fn beat_sheets_read_the_documented_json() { + let sheet = BeatSheet::from_json( + r##"{ + "title": "Hello", + "look": { "theme": "dark", "backdrop": ["#101014", "#22223a"], "motion": "cinematic" }, + "beats": [ + { "type": "card", "text": "One line" }, + { "type": "clip", "moments": [1, 2], "shot": "element", + "focus": { "x": 0.1, "y": 0.2, "w": 0.4, "h": 0.3 } }, + { "type": "clip", "moments": [3] } + ] + }"##, + ) + .expect("parses"); + assert_eq!(sheet.beats.len(), 3); + assert!(sheet.look.music); + assert!(matches!( + sheet.beats[2], + Beat::Clip { + shot: Shot::Auto, + pace: Pace::Auto, + .. + } + )); +} + +#[test] +fn rects_grow_to_an_aspect_inside_the_frame() { + let rect = Rect::new(0.8, 0.8, 0.15, 0.1).with_aspect(16.0 / 9.0, 1.6); + assert!(rect.right() <= 1.0 + 1e-9 && rect.bottom() <= 1.0 + 1e-9); + let pixel_aspect = rect.w * 3200.0 / (rect.h * 2000.0); + assert!((pixel_aspect - 16.0 / 9.0).abs() < 1e-6); +} + +#[test] +fn a_moment_is_shown_once() { + let signals = sample_signals(); + let id = signals + .moments + .iter() + .find(|moment| moment.kind == MomentKind::Click) + .expect("a click") + .id; + let clip = || Beat::Clip { + moments: vec![id], + shot: Shot::Wide, + focus: None, + pace: Pace::Auto, + caption: None, + }; + let sheet = BeatSheet { + title: None, + look: Look::default(), + beats: vec![clip(), clip()], + }; + let compiled = compile( + &ProjectConfiguration::default(), + &signals, + &sheet, + &CompileOptions::default(), + ) + .expect("compiles"); + assert_eq!(compiled.shots.len(), 1); +} From e1ea757f4f817934b711ba9c870908aa6a442abf Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:55:30 +0000 Subject: [PATCH 2/7] feat: add cap demo commands and MCP tools --- Cargo.lock | 11 + apps/cli/Cargo.toml | 1 + apps/cli/src/demo.rs | 816 +++++++++++++++++++++++++++++++++++++++++++ apps/cli/src/main.rs | 4 + apps/cli/src/mcp.rs | 88 +++++ 5 files changed, 920 insertions(+) create mode 100644 apps/cli/src/demo.rs diff --git a/Cargo.lock b/Cargo.lock index dbd5474d81c..5b111c26729 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1086,6 +1086,7 @@ dependencies = [ "cap-automation", "cap-camera", "cap-cli-install", + "cap-director", "cap-editor", "cap-enc-ffmpeg", "cap-export", @@ -1336,6 +1337,16 @@ dependencies = [ "workspace-hack", ] +[[package]] +name = "cap-director" +version = "0.1.0" +dependencies = [ + "cap-project", + "serde", + "serde_json", + "workspace-hack", +] + [[package]] name = "cap-editor" version = "0.1.0" diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml index ab966828c77..3bdbdb0f1ea 100644 --- a/apps/cli/Cargo.toml +++ b/apps/cli/Cargo.toml @@ -17,6 +17,7 @@ cap-timestamp = { path = "../../crates/timestamp" } cap-utils = { path = "../../crates/utils" } relative-path = "1.9.3" cap-automation = { path = "../../crates/automation" } +cap-director = { path = "../../crates/director" } cap-camera = { path = "../../crates/camera" } cap-cli-install = { path = "../../crates/cli-install" } scap-targets = { path = "../../crates/scap-targets" } diff --git a/apps/cli/src/demo.rs b/apps/cli/src/demo.rs new file mode 100644 index 00000000000..6bbe5dd7965 --- /dev/null +++ b/apps/cli/src/demo.rs @@ -0,0 +1,816 @@ +use std::path::{Path, PathBuf}; + +use cap_director::{ + BeatSheet, CompileOptions, ElementHint, GrayFrame, MusicTrack, ShotReport, SignalInput, + Signals, VisualSample, +}; +use cap_project::{ + CursorEvents, KeyboardEvents, ProjectConfiguration, RecordingMeta, RecordingMetaInner, + StudioRecordingMeta, +}; +use cap_rendering::ProjectRecordingsMeta; +use clap::{Args, Subcommand}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::{OutputFormat, credentials, finish_json, resolve_format, write_json}; + +const ANALYSIS_FPS: f64 = 10.0; +const ANALYSIS_WIDTH: u32 = 192; +const FRAME_WIDTH: u32 = 1280; +const FRAME_JPEG_QUALITY: u8 = 82; +const PLANNER_FRAME_WIDTH: u32 = 960; +const PLANNER_FRAME_JPEG_QUALITY: u8 = 72; +const PLANNER_MAX_FRAMES: usize = 24; +const DECODE_THREADS: usize = 4; +const WORK_DIR: &str = "director"; +const ELEMENTS_FILE: &str = "director-elements.json"; +const BACKUP_FILE: &str = "project-config.before-demo.json"; +const PLAN_TIMEOUT_SECS: u64 = 180; +const VISUAL_CACHE_VERSION: u32 = 2; + +#[derive(Args)] +pub struct DemoArgs { + #[command(subcommand)] + command: DemoCommands, +} + +#[derive(Subcommand)] +enum DemoCommands { + /// Turn a recording into an edited demo in one step + Auto(AutoArgs), + /// Read what happened in a recording as numbered moments + Signals(SignalsArgs), + /// Write a beat sheet for a recording + Plan(PlanArgs), + /// Apply a beat sheet to a recording's timeline + Apply(ApplyArgs), + /// Put back the timeline a recording had before the demo edit + Undo(ProjectOnly), + /// Print how to write a beat sheet + Guide(GuideArgs), +} + +#[derive(Args)] +struct ProjectOnly { + /// Path to the '.cap' project + project_path: PathBuf, + #[arg(long, value_enum, default_value_t = OutputFormat::Text)] + format: OutputFormat, +} + +#[derive(Args)] +struct GuideArgs { + #[arg(long, value_enum, default_value_t = OutputFormat::Text)] + format: OutputFormat, +} + +#[derive(Args)] +struct SignalsArgs { + /// Path to the '.cap' project + project_path: PathBuf, + /// Also write a frame of every moment as JPEG files into this folder + #[arg(long)] + frames: Option, + /// Write only the smaller set of frames Cap's own planner is sent + #[arg(long, requires = "frames")] + planner_frames: bool, + #[arg(long, value_enum, default_value_t = OutputFormat::Json)] + format: OutputFormat, +} + +#[derive(Args)] +struct PlanArgs { + /// Path to the '.cap' project + project_path: PathBuf, + /// What the demo should show, in a sentence + #[arg(long)] + goal: Option, + /// Plan on this machine from the signals alone, without a model + #[arg(long)] + local: bool, + /// Write the beat sheet to this file instead of stdout + #[arg(long, short)] + output: Option, +} + +#[derive(Args)] +struct ApplyArgs { + /// Path to the '.cap' project + project_path: PathBuf, + /// Beat sheet JSON file, or '-' for stdin + #[arg(long)] + plan: PathBuf, + /// Music file to lay under the demo + #[arg(long)] + music: Option, + /// Font family for cards and captions + #[arg(long)] + font: Option, + #[arg(long, value_enum, default_value_t = OutputFormat::Text)] + format: OutputFormat, +} + +#[derive(Args)] +struct AutoArgs { + /// Path to the '.cap' project + project_path: PathBuf, + /// What the demo should show, in a sentence + #[arg(long)] + goal: Option, + /// Plan on this machine from the signals alone, without a model + #[arg(long)] + local: bool, + /// Music file to lay under the demo + #[arg(long)] + music: Option, + /// Font family for cards and captions + #[arg(long)] + font: Option, + #[arg(long, value_enum, default_value_t = OutputFormat::Text)] + format: OutputFormat, +} + +impl DemoArgs { + pub async fn run(self, json: bool) -> Result<(), String> { + match self.command { + DemoCommands::Guide(args) => { + let format = resolve_format(json, args.format); + finish_json(format, guide(format)) + } + DemoCommands::Signals(args) => { + let format = resolve_format(json, args.format); + finish_json(format, run_signals(args)) + } + DemoCommands::Plan(args) => { + let format = if json { + OutputFormat::Json + } else { + OutputFormat::Text + }; + finish_json(format, run_plan(args).await) + } + DemoCommands::Apply(args) => { + let format = resolve_format(json, args.format); + finish_json(format, run_apply(args, format)) + } + DemoCommands::Undo(args) => { + let format = resolve_format(json, args.format); + finish_json(format, undo(&args.project_path, format)) + } + DemoCommands::Auto(args) => { + let format = resolve_format(json, args.format); + finish_json(format, run_auto(args, format).await) + } + } + } +} + +struct LoadedClip { + index: u32, + display: PathBuf, + duration: f64, + width: u32, + height: u32, + cursor: CursorEvents, + keyboard: KeyboardEvents, + elements: Vec, +} + +#[derive(Deserialize)] +struct ElementsFile { + #[serde(default)] + events: Vec, +} + +fn load_clips(project_path: &Path) -> Result, String> { + let meta = RecordingMeta::load_for_project(project_path) + .map_err(|e| format!("Failed to load recording meta: {e}"))?; + let RecordingMetaInner::Studio(studio) = &meta.inner else { + return Err("Demos are made from Studio recordings".to_string()); + }; + let StudioRecordingMeta::MultipleSegments { inner } = studio.as_ref() else { + return Err( + "This recording uses an older layout; open it in Cap once, then try again".to_string(), + ); + }; + let recordings = ProjectRecordingsMeta::new(&meta.project_path, studio)?; + let elements = std::fs::read(project_path.join(ELEMENTS_FILE)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .map(|file| file.events) + .unwrap_or_default(); + + Ok(inner + .segments + .iter() + .zip(&recordings.segments) + .enumerate() + .map(|(index, (segment, recording))| LoadedClip { + index: index as u32, + display: meta.path(&segment.display.path), + duration: recording.display.duration, + width: recording.display.width, + height: recording.display.height, + cursor: segment.cursor_events(&meta), + keyboard: segment.keyboard_events(&meta), + elements: if index == 0 { + elements.clone() + } else { + Vec::new() + }, + }) + .collect()) +} + +struct WantedFrame { + time: f64, + path: PathBuf, +} + +#[derive(Clone, Copy)] +struct FrameFormat { + width: u32, + quality: u8, +} + +const FULL_FRAMES: FrameFormat = FrameFormat { + width: FRAME_WIDTH, + quality: FRAME_JPEG_QUALITY, +}; +const PLANNER_FRAMES: FrameFormat = FrameFormat { + width: PLANNER_FRAME_WIDTH, + quality: PLANNER_FRAME_JPEG_QUALITY, +}; + +/// One pass over a screen track: small grayscale frames at `ANALYSIS_FPS` +/// when `analyze` is set, and a JPEG of the first frame at or after each +/// wanted time. +fn scan_video( + display: &Path, + analyze: bool, + wanted: &mut [WantedFrame], + frame: FrameFormat, +) -> Result, String> { + wanted.sort_by(|a, b| a.time.total_cmp(&b.time)); + let mut input = ffmpeg::format::input(&display).map_err(|e| format!("open video: {e}"))?; + let stream = input + .streams() + .best(ffmpeg::media::Type::Video) + .ok_or("no video stream")?; + let stream_index = stream.index(); + let time_base = stream.time_base(); + let seconds_per_tick = + f64::from(time_base.numerator()) / f64::from(time_base.denominator()).max(1.0); + let first_tick = match stream.start_time() { + ffmpeg::ffi::AV_NOPTS_VALUE => 0, + start => start, + }; + + let mut context = ffmpeg::codec::Context::from_parameters(stream.parameters()) + .map_err(|e| format!("video params: {e}"))?; + context.set_threading(ffmpeg::threading::Config::count(DECODE_THREADS)); + let mut decoder = context + .decoder() + .video() + .map_err(|e| format!("video decoder: {e}"))?; + decoder.set_packet_time_base(time_base); + if decoder.width() == 0 || decoder.height() == 0 { + return Err("The screen track has no picture".to_string()); + } + + let scaled_height = |width: u32| { + ((u64::from(decoder.height()) * u64::from(width) / u64::from(decoder.width())).max(2) + as u32 + / 2) + * 2 + }; + let gray_size = (ANALYSIS_WIDTH, scaled_height(ANALYSIS_WIDTH)); + let frame_width = frame.width.min(decoder.width() / 2 * 2); + let frame_size = (frame_width, scaled_height(frame_width)); + let mut gray_scaler = ffmpeg::software::scaling::context::Context::get( + decoder.format(), + decoder.width(), + decoder.height(), + ffmpeg::format::Pixel::GRAY8, + gray_size.0, + gray_size.1, + ffmpeg::software::scaling::flag::Flags::AREA, + ) + .map_err(|e| format!("create scaler: {e}"))?; + let mut frame_scaler = ffmpeg::software::scaling::context::Context::get( + decoder.format(), + decoder.width(), + decoder.height(), + ffmpeg::format::Pixel::RGB24, + frame_size.0, + frame_size.1, + ffmpeg::software::scaling::flag::Flags::BICUBIC, + ) + .map_err(|e| format!("create scaler: {e}"))?; + + let mut frames = Vec::new(); + let mut next_sample = 0.0f64; + let mut next_wanted = 0usize; + let mut decoded = ffmpeg::frame::Video::empty(); + let mut gray = ffmpeg::frame::Video::empty(); + let mut color = ffmpeg::frame::Video::empty(); + let mut drain = |decoder: &mut ffmpeg::decoder::Video, + frames: &mut Vec, + wanted: &[WantedFrame]| + -> Result { + while decoder.receive_frame(&mut decoded).is_ok() { + let ticks = decoded + .timestamp() + .or_else(|| decoded.pts()) + .unwrap_or(first_tick); + let time = (ticks - first_tick) as f64 * seconds_per_tick; + if analyze && time + 1e-6 >= next_sample { + next_sample = (time + 1.0 / ANALYSIS_FPS).max(next_sample + 1.0 / ANALYSIS_FPS); + gray_scaler + .run(&decoded, &mut gray) + .map_err(|e| format!("scale frame: {e}"))?; + let stride = gray.stride(0); + let (width, height) = (gray_size.0 as usize, gray_size.1 as usize); + let mut data = Vec::with_capacity(width * height); + for row in gray.data(0).chunks(stride).take(height) { + data.extend_from_slice(&row[..width]); + } + frames.push(GrayFrame { + t: time, + width, + height, + data, + }); + } + while let Some(want) = wanted.get(next_wanted) + && time + 1e-6 >= want.time + { + next_wanted += 1; + frame_scaler + .run(&decoded, &mut color) + .map_err(|e| format!("scale frame: {e}"))?; + let stride = color.stride(0); + let (width, height) = (frame_size.0 as usize, frame_size.1 as usize); + let mut data = Vec::with_capacity(width * height * 3); + for row in color.data(0).chunks(stride).take(height) { + data.extend_from_slice(&row[..width * 3]); + } + let file = std::fs::File::create(&want.path) + .map_err(|e| format!("write {}: {e}", want.path.display()))?; + image::codecs::jpeg::JpegEncoder::new_with_quality( + std::io::BufWriter::new(file), + frame.quality, + ) + .encode( + &data, + frame_size.0, + frame_size.1, + image::ExtendedColorType::Rgb8, + ) + .map_err(|e| format!("encode frame: {e}"))?; + } + if !analyze && next_wanted >= wanted.len() { + return Ok(false); + } + } + Ok(true) + }; + + for (stream, packet) in input.packets() { + if stream.index() != stream_index { + continue; + } + if decoder.send_packet(&packet).is_err() { + continue; + } + if !drain(&mut decoder, &mut frames, wanted)? { + return Ok(frames); + } + } + if decoder.send_eof().is_ok() { + drain(&mut decoder, &mut frames, wanted)?; + } + Ok(frames) +} + +#[derive(Serialize, Deserialize)] +struct VisualCache { + #[serde(default)] + version: u32, + bytes: u64, + modified: u64, + samples: Vec, +} + +fn file_identity(path: &Path) -> (u64, u64) { + std::fs::metadata(path) + .map(|meta| { + let modified = meta + .modified() + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |since| since.as_secs()); + (meta.len(), modified) + }) + .unwrap_or_default() +} + +fn visual_track(project_path: &Path, clip: &LoadedClip) -> Result, String> { + let cache_path = project_path + .join(WORK_DIR) + .join(format!("visual-{}.json", clip.index)); + let (bytes, modified) = file_identity(&clip.display); + if let Some(cache) = std::fs::read(&cache_path) + .ok() + .and_then(|data| serde_json::from_slice::(&data).ok()) + .filter(|cache| { + cache.version == VISUAL_CACHE_VERSION + && cache.bytes == bytes + && cache.modified == modified + }) + { + return Ok(cache.samples); + } + let frames = scan_video(&clip.display, true, &mut [], FULL_FRAMES)?; + let samples = cap_director::visual_samples(&frames); + if std::fs::create_dir_all(project_path.join(WORK_DIR)).is_ok() { + let cache = VisualCache { + version: VISUAL_CACHE_VERSION, + bytes, + modified, + samples: samples.clone(), + }; + if let Ok(data) = serde_json::to_vec(&cache) { + let _ = std::fs::write(&cache_path, data); + } + } + Ok(samples) +} + +fn signals_for(project_path: &Path) -> Result<(Signals, Vec), String> { + let clips = load_clips(project_path)?; + let visual = clips + .iter() + .map(|clip| visual_track(project_path, clip)) + .collect::, _>>()?; + let inputs: Vec> = clips + .iter() + .zip(&visual) + .map(|(clip, visual)| SignalInput { + clip: clip.index, + duration: clip.duration, + frame_width: clip.width, + frame_height: clip.height, + cursor: &clip.cursor, + keyboard: &clip.keyboard, + visual, + elements: &clip.elements, + }) + .collect(); + Ok((cap_director::analyze(&inputs), clips)) +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MomentFrame { + pub moment: u32, + pub when: &'static str, + pub time: f64, + pub path: PathBuf, +} + +/// Which frames to write: every moment's action and result, or the most +/// telling frames that fit in one request to the planner (results of the +/// heaviest moments first, then their actions). +fn frame_picks(signals: &Signals, limit: Option) -> Vec<(u32, &'static str)> { + let mut picks = Vec::new(); + let Some(limit) = limit else { + for moment in &signals.moments { + picks.push((moment.id, "action")); + picks.push((moment.id, "result")); + } + return picks; + }; + let mut ranked: Vec<_> = signals.moments.iter().collect(); + ranked.sort_by(|a, b| b.weight.total_cmp(&a.weight).then(a.id.cmp(&b.id))); + for when in ["result", "action"] { + for moment in &ranked { + if picks.len() < limit { + picks.push((moment.id, when)); + } + } + } + picks +} + +fn write_frames( + signals: &Signals, + clips: &[LoadedClip], + dir: &Path, + format: FrameFormat, + limit: Option, +) -> Result, String> { + std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; + let picks = frame_picks(signals, limit); + let mut written = Vec::new(); + for clip in clips { + let mut wanted = Vec::new(); + for moment in signals.moments.iter().filter(|m| m.clip == clip.index) { + let last = (clip.duration - 0.1).max(0.0); + for (when, time) in [ + ("action", moment.at.min(last)), + ("result", (moment.end - 0.05).clamp(0.0, last)), + ] { + if !picks.contains(&(moment.id, when)) { + continue; + } + let path = dir.join(format!("moment-{:02}-{when}.jpg", moment.id)); + wanted.push(WantedFrame { + time, + path: path.clone(), + }); + written.push(MomentFrame { + moment: moment.id, + when, + time, + path, + }); + } + } + scan_video(&clip.display, false, &mut wanted, format)?; + } + Ok(written) +} + +pub fn signals_value( + project_path: &Path, + frames: Option<&Path>, + for_planner: bool, +) -> Result { + let (signals, clips) = signals_for(project_path)?; + let frames = match frames { + Some(dir) if for_planner => write_frames( + &signals, + &clips, + dir, + PLANNER_FRAMES, + Some(PLANNER_MAX_FRAMES), + )?, + Some(dir) => write_frames(&signals, &clips, dir, FULL_FRAMES, None)?, + None => Vec::new(), + }; + let mut value = serde_json::to_value(signals.brief()).map_err(|e| e.to_string())?; + if !frames.is_empty() { + value["frames"] = serde_json::to_value(frames).map_err(|e| e.to_string())?; + } + Ok(value) +} + +fn run_signals(args: SignalsArgs) -> Result<(), String> { + write_json(&signals_value( + &args.project_path, + args.frames.as_deref(), + args.planner_frames, + )?) +} + +fn guide(format: OutputFormat) -> Result<(), String> { + match format { + OutputFormat::Json => write_json(&json!({ "guide": cap_director::guide::PLANNER_GUIDE })), + OutputFormat::Text => { + println!("{}", cap_director::guide::PLANNER_GUIDE); + Ok(()) + } + } +} + +fn load_base(project_path: &Path) -> Result { + match ProjectConfiguration::load(project_path) { + Ok(config) => Ok(config), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + Ok(ProjectConfiguration::for_new_project()) + } + Err(e) => Err(format!("Failed to load project config: {e}")), + } +} + +fn music_track(project_path: &Path, music: Option<&Path>) -> Result, String> { + let Some(source) = music else { + return Ok(None); + }; + let input = ffmpeg::format::input(&source).map_err(|e| format!("open music: {e}"))?; + let duration = input.duration() as f64 / f64::from(ffmpeg::ffi::AV_TIME_BASE); + if !duration.is_finite() || duration <= 0.0 { + return Err("The music file has no length".to_string()); + } + let stem = source + .file_stem() + .and_then(|stem| stem.to_str()) + .unwrap_or("music"); + let extension = source + .extension() + .and_then(|extension| extension.to_str()) + .unwrap_or("mp3"); + let relative = format!("assets/audio/demo-{stem}.{extension}"); + let target = project_path.join(&relative); + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent).map_err(|e| format!("create audio folder: {e}"))?; + } + std::fs::copy(source, &target).map_err(|e| format!("copy music: {e}"))?; + Ok(Some(MusicTrack { + path: relative, + name: stem.to_string(), + duration, + })) +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Applied { + pub project_path: PathBuf, + pub duration: f64, + pub shots: Vec, +} + +pub fn apply_sheet( + project_path: &Path, + sheet: &BeatSheet, + music: Option<&Path>, + font: Option, +) -> Result { + let (signals, _) = signals_for(project_path)?; + let config_path = project_path.join("project-config.json"); + let backup_path = project_path.join(BACKUP_FILE); + let base = if backup_path.exists() { + let bytes = std::fs::read(&backup_path).map_err(|e| format!("read backup: {e}"))?; + serde_json::from_slice(&bytes).map_err(|e| format!("read backup: {e}"))? + } else { + let base = load_base(project_path)?; + if config_path.exists() { + std::fs::copy(&config_path, &backup_path) + .map_err(|e| format!("Failed to keep the current timeline: {e}"))?; + } + base + }; + let options = CompileOptions { + music: music_track(project_path, music)?, + font_family: font, + }; + let compiled = cap_director::compile(&base, &signals, sheet, &options)?; + compiled + .config + .write(project_path) + .map_err(|e| format!("Failed to write project config: {e}"))?; + Ok(Applied { + project_path: project_path.to_path_buf(), + duration: compiled.duration, + shots: compiled.shots, + }) +} + +fn print_applied(applied: &Applied, format: OutputFormat) -> Result<(), String> { + match format { + OutputFormat::Json => write_json(applied), + OutputFormat::Text => { + println!( + "Demo timeline written: {:.1} s, {} shots", + applied.duration, + applied.shots.len() + ); + for shot in &applied.shots { + println!(" {:>5.1} to {:>5.1} {}", shot.start, shot.end, shot.shot); + } + Ok(()) + } + } +} + +fn read_sheet(path: &Path) -> Result { + let json = if path == Path::new("-") { + std::io::read_to_string(std::io::stdin()).map_err(|e| format!("read stdin: {e}"))? + } else { + std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))? + }; + BeatSheet::from_json(&json) +} + +fn run_apply(args: ApplyArgs, format: OutputFormat) -> Result<(), String> { + let sheet = read_sheet(&args.plan)?; + let applied = apply_sheet(&args.project_path, &sheet, args.music.as_deref(), args.font)?; + print_applied(&applied, format) +} + +fn undo(project_path: &Path, format: OutputFormat) -> Result<(), String> { + let backup_path = project_path.join(BACKUP_FILE); + let config_path = project_path.join("project-config.json"); + if backup_path.exists() { + std::fs::rename(&backup_path, &config_path) + .map_err(|e| format!("Failed to restore the timeline: {e}"))?; + } else { + return Err("This recording has no demo edit to undo".to_string()); + } + match format { + OutputFormat::Json => write_json(&json!({ "ok": true })), + OutputFormat::Text => { + println!("Timeline restored"); + Ok(()) + } + } +} + +async fn cloud_plan( + project_path: &Path, + signals: &Signals, + clips: &[LoadedClip], + goal: Option<&str>, +) -> Result { + use base64::Engine; + + let creds = credentials::resolve().map_err(|_| { + "Planning a demo with Cap AI needs a Cap Pro sign-in. Sign in to Cap Desktop or set CAP_API_KEY, or pass --local to plan without a model".to_string() + })?; + let frames_dir = project_path.join(WORK_DIR).join("planner-frames"); + let frames = write_frames( + signals, + clips, + &frames_dir, + PLANNER_FRAMES, + Some(PLANNER_MAX_FRAMES), + )?; + let images = frames + .iter() + .map(|frame| { + let bytes = std::fs::read(&frame.path) + .map_err(|e| format!("read {}: {e}", frame.path.display()))?; + Ok(json!({ + "moment": frame.moment, + "when": frame.when, + "jpegBase64": base64::engine::general_purpose::STANDARD.encode(bytes), + })) + }) + .collect::, String>>()?; + let body = json!({ + "goal": goal, + "signals": signals.brief(), + "frames": images, + }); + let response = reqwest::Client::new() + .post(format!("{}/api/desktop/demos/plan", creds.server)) + .header("Authorization", format!("Bearer {}", creds.api_key)) + .timeout(std::time::Duration::from_secs(PLAN_TIMEOUT_SECS)) + .json(&body) + .send() + .await + .map_err(|e| format!("Could not reach Cap: {e}"))?; + let status = response.status(); + let text = response + .text() + .await + .map_err(|e| format!("Could not read Cap's answer: {e}"))?; + if status == reqwest::StatusCode::PAYMENT_REQUIRED || status == reqwest::StatusCode::FORBIDDEN { + return Err( + "Planning a demo with Cap AI is part of Cap Pro. Pass --local to plan without a model" + .to_string(), + ); + } + if !status.is_success() { + return Err(format!("Cap could not plan this demo ({status})")); + } + #[derive(Deserialize)] + struct Planned { + plan: BeatSheet, + } + serde_json::from_str::(&text) + .map(|planned| planned.plan) + .map_err(|e| format!("Cap's plan could not be read: {e}")) +} + +async fn plan_sheet( + project_path: &Path, + goal: Option<&str>, + local: bool, +) -> Result { + let (signals, clips) = signals_for(project_path)?; + if local { + return Ok(cap_director::heuristic::plan(&signals)); + } + cloud_plan(project_path, &signals, &clips, goal).await +} + +async fn run_plan(args: PlanArgs) -> Result<(), String> { + let sheet = plan_sheet(&args.project_path, args.goal.as_deref(), args.local).await?; + match args.output { + Some(path) => { + let json = serde_json::to_string_pretty(&sheet).map_err(|e| e.to_string())?; + std::fs::write(&path, json).map_err(|e| format!("write {}: {e}", path.display())) + } + None => write_json(&sheet), + } +} + +async fn run_auto(args: AutoArgs, format: OutputFormat) -> Result<(), String> { + let sheet = plan_sheet(&args.project_path, args.goal.as_deref(), args.local).await?; + let applied = apply_sheet(&args.project_path, &sheet, args.music.as_deref(), args.font)?; + print_applied(&applied, format) +} diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs index 071cd903c89..65efa19b2f2 100644 --- a/apps/cli/src/main.rs +++ b/apps/cli/src/main.rs @@ -8,6 +8,7 @@ mod automation; mod caps; mod confirmation; mod credentials; +mod demo; mod developer_media; mod developers; mod doctor; @@ -200,6 +201,8 @@ enum Commands { ExportPreview(ExportPreview), /// Inspect or validate a '.cap' project Project(ProjectArgs), + /// Turn a recording into an edited demo + Demo(demo::DemoArgs), /// Start a recording or list available capture targets and devices Record(RecordArgs), /// Capture a still screenshot of a screen or window @@ -671,6 +674,7 @@ async fn run(cli: Cli) -> Result<(), CliFailure> { Commands::ExportPreview(e) => e.run().await, Commands::Selftest(args) => args.run(json).await, Commands::Project(args) => args.run(json), + Commands::Demo(args) => args.run(json).await, Commands::Record(RecordArgs { command, args }) => match command { Some(RecordCommands::Start(args)) => args.run(json).await, Some(RecordCommands::Stop(args)) => args.run(json).await, diff --git a/apps/cli/src/mcp.rs b/apps/cli/src/mcp.rs index 4acc5446f7d..2f19d55a13b 100644 --- a/apps/cli/src/mcp.rs +++ b/apps/cli/src/mcp.rs @@ -454,6 +454,29 @@ struct DeveloperTranscriptCreateInput { confirmed: bool, } +#[derive(Debug, Deserialize, schemars::JsonSchema)] +struct DemoSignalsInput { + /// Absolute path to the '.cap' project folder of a Studio recording + project_path: String, + /// Folder to write a JPEG of every moment into. Defaults to director/frames inside the project + #[serde(default)] + frames_dir: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +struct DemoApplyInput { + /// Absolute path to the '.cap' project folder of a Studio recording + project_path: String, + /// The beat sheet object, in the shape the guide from demo_signals describes + plan: Value, + /// Absolute path to a music file to lay under the demo + #[serde(default)] + music_path: Option, + /// Font family for cards and captions + #[serde(default)] + font: Option, +} + #[derive(Debug, Deserialize, schemars::JsonSchema)] struct DeveloperTranscriptInput { /// App id from developer_apps_list @@ -4042,6 +4065,71 @@ impl CapMcpServer { .await, ) } + + #[tool( + name = "demo_signals", + description = "Read a local Studio recording as numbered moments (each click and run of typing with the screen area it happened in), write a JPEG of every moment, and return the guide for writing a beat sheet. First step of turning a recording into an edited demo: look at the frames, write the beat sheet, then call demo_apply. Reads local files only", + annotations( + read_only_hint = false, + destructive_hint = false, + idempotent_hint = false, + open_world_hint = false + ) + )] + async fn demo_signals( + &self, + Parameters(input): Parameters, + ) -> CallToolResult { + let project = std::path::PathBuf::from(&input.project_path); + let frames = input + .frames_dir + .map(std::path::PathBuf::from) + .unwrap_or_else(|| project.join("director").join("frames")); + let read = tokio::task::spawn_blocking(move || { + crate::demo::signals_value(&project, Some(&frames), false) + }) + .await; + Self::result(match read { + Ok(Ok(mut value)) => { + value["guide"] = json!(cap_director::guide::PLANNER_GUIDE); + Ok(value) + } + Ok(Err(message)) => Err(Self::invalid(message)), + Err(_) => Err(Self::invalid("The recording could not be read")), + }) + } + + #[tool( + name = "demo_apply", + description = "Apply a beat sheet to a local Studio recording: cuts dead time, speeds up typing, frames every shot, adds the cards and writes an ordinary editable timeline. The timeline the recording had before is kept and `cap demo undo` restores it. Export afterwards with `cap export`. Call demo_signals first for the moments and the guide", + annotations( + read_only_hint = false, + destructive_hint = false, + idempotent_hint = false, + open_world_hint = false + ) + )] + async fn demo_apply(&self, Parameters(input): Parameters) -> CallToolResult { + let sheet: cap_director::BeatSheet = match serde_json::from_value(input.plan) { + Ok(sheet) => sheet, + Err(error) => { + return Self::result(Err(Self::invalid(format!("Invalid beat sheet: {error}")))); + } + }; + let project = std::path::PathBuf::from(&input.project_path); + let music = input.music_path.map(std::path::PathBuf::from); + let font = input.font; + let applied = tokio::task::spawn_blocking(move || { + crate::demo::apply_sheet(&project, &sheet, music.as_deref(), font) + }) + .await; + Self::result(match applied { + Ok(Ok(applied)) => serde_json::to_value(applied) + .map_err(|_| Self::invalid("The result could not be represented")), + Ok(Err(message)) => Err(Self::invalid(message)), + Err(_) => Err(Self::invalid("The beat sheet could not be applied")), + }) + } } #[tool_handler(router = self.tool_router)] From 316eb7e2dc70e99664c636536f6be22011eef756 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:55:30 +0000 Subject: [PATCH 3/7] feat: add demo planner route --- apps/web/__tests__/unit/demo-plan.test.ts | 142 +++++++++++++ apps/web/app/api/desktop/[...route]/demos.ts | 111 ++++++++++ apps/web/app/api/desktop/[...route]/route.ts | 2 + apps/web/lib/demos/beat-sheet.ts | 206 +++++++++++++++++++ apps/web/lib/demos/plan.ts | 70 +++++++ apps/web/lib/demos/prompt.ts | 81 ++++++++ 6 files changed, 612 insertions(+) create mode 100644 apps/web/__tests__/unit/demo-plan.test.ts create mode 100644 apps/web/app/api/desktop/[...route]/demos.ts create mode 100644 apps/web/lib/demos/beat-sheet.ts create mode 100644 apps/web/lib/demos/plan.ts create mode 100644 apps/web/lib/demos/prompt.ts diff --git a/apps/web/__tests__/unit/demo-plan.test.ts b/apps/web/__tests__/unit/demo-plan.test.ts new file mode 100644 index 00000000000..5aa0595f1b1 --- /dev/null +++ b/apps/web/__tests__/unit/demo-plan.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it, vi } from "vitest"; + +const generateText = vi.hoisted(() => vi.fn()); +vi.mock("ai", () => ({ generateText })); + +const sheet = await import("@/lib/demos/beat-sheet"); +const { buildDemoPrompt } = await import("@/lib/demos/prompt"); +const { planDemo, DemoPlanUnavailableError } = await import("@/lib/demos/plan"); + +const moment = (id: number, start: number, clip = 0) => ({ + id, + clip, + kind: "click" as const, + start, + end: start + 2, + at: start + 0.5, + focus: { x: 0.2, y: 0.2, w: 0.3, h: 0.3 }, + weight: 1, +}); + +const request = sheet.demoPlanRequestSchema.parse({ + goal: "Show the export", + signals: { + version: 1, + clips: [{ clip: 0, duration: 60, frameWidth: 3200, frameHeight: 2000 }], + moments: [moment(1, 2), moment(2, 10), moment(3, 20)], + }, + frames: [{ moment: 1, when: "result", jpegBase64: "AAAA" }], +}); + +describe("parseBeatSheet", () => { + it("reads a fenced answer and keeps only moments the recording has", () => { + const plan = sheet.parseBeatSheet( + '```json\n{"title":"T","look":{"theme":"dark","backdrop":["#101014","#22223a"]},"beats":[{"type":"card","text":"Hello"},{"type":"clip","moments":[3,1,99,1],"shot":"element"},{"type":"clip","moments":[42]}]}\n```', + request.signals.moments, + ); + expect(plan.look).toEqual({ + theme: "dark", + backdrop: ["#101014", "#22223a"], + motion: "flat", + music: true, + }); + expect(plan.beats).toEqual([ + { type: "card", text: "Hello" }, + { type: "clip", moments: [1, 3], shot: "element", pace: "auto" }, + ]); + }); + + it("falls back on a shot or a focus it does not understand", () => { + const plan = sheet.parseBeatSheet( + '{"beats":[{"type":"clip","moments":[2],"shot":"dolly","focus":{"x":0.9,"y":0.9,"w":0.5,"h":0.5}}]}', + request.signals.moments, + ); + expect(plan.beats).toEqual([ + { type: "clip", moments: [2], shot: "auto", pace: "auto" }, + ]); + }); + + it("shows a moment only the first time it is named", () => { + const plan = sheet.parseBeatSheet( + '{"beats":[{"type":"clip","moments":[1,2]},{"type":"clip","moments":[2,3]},{"type":"clip","moments":[1]}]}', + request.signals.moments, + ); + expect( + plan.beats.map((beat) => beat.type === "clip" && beat.moments), + ).toEqual([[1, 2], [3]]); + }); + + it("refuses an answer with no usable clip", () => { + expect(() => + sheet.parseBeatSheet( + '{"beats":[{"type":"card","text":"Only words"}]}', + request.signals.moments, + ), + ).toThrow(sheet.DemoPlanInvalidError); + expect(() => + sheet.parseBeatSheet("no plan here", request.signals.moments), + ).toThrow(sheet.DemoPlanInvalidError); + }); +}); + +describe("demoPlanRequestSchema", () => { + it("refuses frames that are not base64 and too many frames", () => { + const frame = { moment: 1, when: "result", jpegBase64: "AAAA" }; + expect( + sheet.demoPlanRequestSchema.safeParse({ + ...request, + frames: [{ ...frame, jpegBase64: "