Open source CapCut alternative.
TypeScript
feat(site): cut to the music [rebuild]
David Le2bdb50abe1d5
diff --git a/site/scripts/lib/cut-eval/fixtures.ts b/site/scripts/lib/cut-eval/fixtures.tsindex a713f99a..4f0fa5ea 100644--- a/site/scripts/lib/cut-eval/fixtures.ts+++ b/site/scripts/lib/cut-eval/fixtures.ts@@ -22,6 +22,7 @@ export const SAFE_TOOLS = new Set(["capture_frame","watch_video","detect_silence",+ "detect_beats","listen_audio","read_color_stats","library_list",@@ -620,5 +621,6 @@ export function serveSafeTool(name: string, state: unknown): unknown {if (name === "list_skills") return { skills: AI_SKILL_INDEX };if (name === "library_list") return { folders: [], assets: [], templates: [] };if (name === "detect_silence") return { silences: [] };+ if (name === "detect_beats") return { bpm: 0, beats: [] };return { ok: true };}diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.tsindex 30049302..3095eeda 100644--- a/site/src/cut/components/AiPanel.tools.ts+++ b/site/src/cut/components/AiPanel.tools.ts@@ -7,7 +7,7 @@* (the `server: true` tools run in the engine and take no browser handler).*/-import { num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";+import { bool, num, obj, str, type AiToolDef } from "@/cut/lib/aiToolDef";export const AI_PANEL_TOOLS = [{@@ -65,6 +65,18 @@ export const AI_PANEL_TOOLS = [min_silence: num("Shortest silent stretch to report, seconds (default 0.35)"),}),},+ {+ name: "detect_beats",+ description:+ "Read a source's musical beat grid — the tempo and where each beat lands — for cutting to the music. Returns bpm and beats in SOURCE seconds; with clip_id it also returns timelineBeats, the beats inside the clip's trimmed range mapped to timeline seconds, ready for split_at. The grid persists on the asset: its clips draw the beats as yellow dots and every drag or trim snaps to them, so one detection serves the whole edit. A stored grid comes back as-is — the user can hand-edit the dots, and their edits hold, and a grid they have edited reports bpm 0 because the tempo is theirs now — so pass regenerate only to re-scan and replace it. Detection always reads the whole source; from/to just window the reply.",+ inputSchema: obj({+ clip_id: str("Clip id — video, overlay, or soundtrack; windows the reply to its trimmed range and maps beats to timeline seconds"),+ asset_id: str("Project asset id (video or audio)"),+ from: num("Source start s (default: the clip's in, else 0)"),+ to: num("Source end s (default: the clip's out, else the source's end)"),+ regenerate: bool("Re-scan and replace a stored grid, dropping any hand edits (default false)"),+ }),+ },{name: "listen_audio",description:diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsxindex a813ef26..50d3ac4a 100644--- a/site/src/cut/components/Inspector.tsx+++ b/site/src/cut/components/Inspector.tsx@@ -1,7 +1,7 @@"use client";-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";-import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Italic, SlidersHorizontal, Smile, Trash2, Type } from "lucide-react";+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Italic, Loader2, SlidersHorizontal, Smile, Trash2, Type } from "lucide-react";import { Button } from "@/components/ui/button";import { EmojiPicker } from "@/cut/components/EmojiPicker";import { FontPicker } from "@/cut/components/FontPicker";@@ -89,6 +89,7 @@ import {SPEED_FLOOR,SPEED_MAX,SPEED_MIN,+ assetIsSilent,clampOverlayPos,type AudioClip,type BoxStyle,@@ -96,12 +97,15 @@ import {type FrameRect,type LayoutId,type EffectOverlay,+ type MediaAsset,type Overlay,type ShapeOverlay,type StickerOverlay,type TextOverlay,type VideoClip,} from "@/cut/lib/types";+import { beatsBusyFor, detectAssetBeats, subscribeBeatsBusy } from "@/cut/lib/media";+import { reportSwallowed } from "@/cut/lib/report";import { GRADE_PRESETS, isNeutralGrade } from "@donkeycut/effects-kit";import {MOVE_STRENGTH_MAX,@@ -535,6 +539,14 @@ function ClipPanel({ clip, onColor }: { clip: VideoClip; onColor: () => void })onCheckedChange={(v) => updateClip(clip.id, { muted: v })}/></Row>+ {asset && !assetIsSilent(asset) && (+ <Row+ label="Beats"+ info="Beat markers detected from the clip's sound, drawn as dots along its bar. Every drag and trim snaps to them; drag a dot to move it, double-click removes it, ⌥-click the clip adds one."+ >+ <BeatsControl asset={asset} />+ </Row>+ )}{/* Picture */}<div className="my-1.5 h-px bg-border" />@@ -783,6 +795,45 @@ function ClipGeneratedAudio({ clip }: { clip: VideoClip }) {);}+/** The Beats row's control: detect (or re-run) the asset's beat grid, and+ * clear it. The dots themselves live on the clip bars — dragged, added+ * (⌥-click), and removed (double-click) there. */+function BeatsControl({ asset }: { asset: MediaAsset }) {+ const busy = useSyncExternalStore(subscribeBeatsBusy, () => beatsBusyFor(asset.id), () => false);+ const grid = asset.beats;+ return (+ <>+ {grid && (+ <Value className="whitespace-nowrap text-muted-foreground">+ {grid.beats.length}+ {grid.bpm > 0 ? `·${Math.round(grid.bpm)} BPM` : " beats"}+ </Value>+ )}+ <Button+ size="sm"+ variant="outline"+ disabled={busy || !!asset.upload}+ onClick={() => {+ void detectAssetBeats(asset).catch((err) => {+ reportSwallowed(`[cut] beat scan failed for ${asset.fileName}`, err);+ });+ }}+ >+ {busy && <Loader2 className="size-3.5 animate-spin" />}+ Detect+ </Button>+ <ResetButton+ title="Clear beats"+ show={!!grid}+ onClick={() => {+ useEditor.getState().pushHistory();+ useEditor.getState().updateAsset(asset.id, { beats: undefined });+ }}+ />+ </>+ );+}+function AudioPanel({ clip }: { clip: AudioClip }) {const asset = useEditor((s) => s.assets.find((a) => a.id === clip.assetId));const updateAudioTransient = useEditor((s) => s.updateAudioTransient);@@ -940,6 +991,14 @@ function AudioPanel({ clip }: { clip: AudioClip }) {onCommit={(v) => commitAudio({ duck: v < 0.999 ? v : undefined })}/></Row>+ {asset && !assetIsSilent(asset) && (+ <Row+ label="Beats"+ info="Beat markers detected from the music, drawn as dots on the clip. Every drag and trim snaps to them; drag a dot to move it, double-click removes it, ⌥-click the clip adds one."+ >+ <BeatsControl asset={asset} />+ </Row>+ )}<Row label="Hidden"><Switchchecked={!!clip.hidden}diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 25a85826..14f8f9b8 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -55,7 +55,7 @@ import { playheadAt, setSkim, skimAt, subscribePlayhead, usePlayhead, useSkim }import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";import { formatTime, formatTimecode } from "@/cut/lib/time";import { EFFECT_LABELS, type EffectId } from "@donkeycut/effects-kit";-import { emptySubtitles, IMAGE_CLIP_SECONDS, isAudioTransition, SHAPE_LABELS, TRANSITION_MAX, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, type ShapeKind } from "@/cut/lib/types";+import { assetIsSilent, emptySubtitles, IMAGE_CLIP_SECONDS, isAudioTransition, SHAPE_LABELS, TRANSITION_MAX, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, type ShapeKind } from "@/cut/lib/types";import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionStyle, VideoClip } from "@/cut/lib/types";import { isLottieAsset } from "@/cut/lib/lottieAssets";import { gradeCssApprox } from "@donkeycut/effects-kit";@@ -3795,7 +3795,15 @@ function ClipView({}}ref={boxRef}data-tl-sel={`clip:${clip.id}`}- onPointerDown={(e) => startLaneMove(e, lane, clip.id, ui)}+ onPointerDown={(e) => {+ // The grid sits on the source, so a muted clip takes a beat the same+ // as a playing one — the same test the Beats row and the snapping use.+ if (e.altKey && !assetIsSilent(asset)) {+ addBeatAt(e, asset, clip, pps);+ return;+ }+ startLaneMove(e, lane, clip.id, ui);+ }}onContextMenu={(e) => {if (asset.type !== "video") return;const rect = e.currentTarget.getBoundingClientRect();@@ -3884,6 +3892,10 @@ function ClipView({width={barW}/>))}+ {/* Drawn wherever the source has a grid: on the band when there is one,+ along the bar's bottom edge when the clip plays silent. Every edge+ snaps to them either way. */}+ <BeatDots asset={asset} from={filmIn} to={filmOut} speed={speed} pps={pps} w={barW} /><spanclassName={cn(trimHandle, "tl-trim-l left-0")}onPointerDown={(e) => startLaneTrim(e, lane, clip.id, "l", ui)}@@ -4720,6 +4732,146 @@ function WaveTile({return <canvas ref={ref} className="absolute top-0" style={{ left, width: tw, height: h }} />;}+/** Rewrite one asset's beat grid by hand: sorted, deduped, clamped to the+ * source; an emptied grid clears. Beats live on the asset in source seconds,+ * so every clip showing the source follows the edit. Editing a dot makes the+ * grid the user's rather than the detector's, so the tempo goes with it+ * (types.ts AssetBeats) — the row reads "N beats" from there on. */+function writeBeats(assetId: string, edit: (beats: number[]) => number[]) {+ const s = useEditor.getState();+ const asset = s.assets.find((a) => a.id === assetId);+ if (!asset) return;+ const next = [+ ...new Set(+ edit(asset.beats?.beats ?? []).map(+ (t) => Math.round(Math.min(asset.duration, Math.max(0, t)) * 1000) / 1000+ )+ ),+ ].sort((a, b) => a - b);+ s.updateAsset(assetId, { beats: next.length ? { beats: next, bpm: 0 } : undefined });+}++/** ⌥-click on a clip bar drops a beat under the pointer, in source seconds. */+function addBeatAt(+ e: React.PointerEvent<HTMLElement>,+ asset: MediaAsset,+ clip: { in: number; speed?: number },+ pps: number+) {+ e.preventDefault();+ e.stopPropagation();+ const rect = e.currentTarget.getBoundingClientRect();+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;+ useEditor.getState().pushHistory();+ writeBeats(asset.id, (list) => [...list, clip.in + ((e.clientX - rect.left) / pps) * speed]);+}++/**+ * One beat on a clip bar: a yellow dot on the bottom edge where the music+ * hits. The grab is its own (startDrag stops the bar's gesture), so dragging+ * a dot retimes the beat — in source seconds, every clip of the asset+ * follows — and a double-click removes it.+ */+function BeatDot({+ assetId,+ duration,+ t,+ from,+ speed,+ pps,+ w,+}: {+ assetId: string;+ /** The source's length, the drag's bound. */+ duration: number;+ /** The beat, source seconds. */+ t: number;+ /** The bar's own source window start and rate. */+ from: number;+ speed: number;+ pps: number;+ /** Visible bar width, px, for parking the edge dots inside it. */+ w: number;+}) {+ return (+ <span+ className="tl-beat absolute bottom-0 z-5 grid h-3.5 w-3 cursor-ew-resize place-items-end justify-center pb-[3px]"+ style={{+ left: Math.min(w - 4, Math.max(4, ((t - from) / speed) * pps)),+ transform: "translateX(-50%)",+ }}+ title="Drag to move, double-click to remove"+ onPointerDown={(e) => {+ const s = useEditor.getState();+ let live = t;+ // The undo step opens on the first movement, so a stray grab that+ // never moves leaves nothing behind.+ let checkpointed = false;+ startDrag(e, {+ onMove: (dx) => {+ if (!checkpointed) {+ checkpointed = true;+ s.pushHistory();+ }+ // Rounded the way the grid stores, so the moved beat is found again.+ const next =+ Math.round(Math.min(duration, Math.max(0, t + (dx / pps) * speed)) * 1000) / 1000;+ const at = live;+ writeBeats(assetId, (list) => list.map((b) => (b === at ? next : b)));+ live = next;+ },+ });+ }}+ onDoubleClick={(e) => {+ e.stopPropagation();+ useEditor.getState().pushHistory();+ writeBeats(assetId, (list) => list.filter((b) => b !== t));+ }}+ >+ <span className="pointer-events-none size-[5px] rounded-full bg-[#ffd60a] shadow-[0_0_0_1px_rgba(0,0,0,0.4)]" />+ </span>+ );+}++/** The asset's beat grid across one clip bar — the dots inside the bar's+ * source window `from..to`. */+function BeatDots({+ asset,+ from,+ to,+ speed,+ pps,+ w,+}: {+ asset: MediaAsset;+ from: number;+ to: number;+ speed: number;+ pps: number;+ w: number;+}) {+ const beats = asset.beats?.beats;+ if (!beats?.length) return null;+ return (+ <>+ {beats+ .filter((b) => b >= from && b <= to)+ .map((b) => (+ <BeatDot+ key={b}+ assetId={asset.id}+ duration={asset.duration}+ t={b}+ from={from}+ speed={speed}+ pps={pps}+ w={w}+ />+ ))}+ </>+ );+}+function AudioView({clip,asset,@@ -4764,6 +4916,7 @@ function AudioView({// The bar is drawn a gutter narrower than the footprint; what sits inside// it measures against that.const barW = Math.max(10, w - CLIP_GAP);+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;if (!asset) return null;@@ -4791,9 +4944,16 @@ function AudioView({zIndex: drag || rowMove === "lift" ? 20 : undefined,}}data-tl-sel={`audio:${clip.id}`}- onPointerDown={(e) => startLaneMove(e, "audio", clip.id, ui)}+ onPointerDown={(e) => {+ if (e.altKey && !assetIsSilent(asset)) {+ addBeatAt(e, asset, clip, pps);+ return;+ }+ startLaneMove(e, "audio", clip.id, ui);+ }}><WaveformCanvas asset={asset} from={clip.in} to={clip.out} w={barW} h={AUDIO_H - 8} className="inset-x-0 inset-y-1" />+ <BeatDots asset={asset} from={clip.in} to={clip.out} speed={speed} pps={pps} w={barW} />{(clip.fadeIn ?? 0) > 0 && (<divclassName="tl-fade-in pointer-events-none absolute inset-y-0 left-0 bg-gradient-to-r from-black/45 to-transparent"diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 8a2db709..074603b6 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -70,6 +70,8 @@ import {import { fetchNotes } from "./notes";import {captureFreezeFrame,+ beatlessFor,+ detectAssetBeats,detectSilenceClientSide,enrichAsset,ensurePeaks,@@ -133,6 +135,7 @@ import {allFonts,ANIM_DEFAULT_SECONDS,ANIM_STYLE_IDS,+ assetIsSilent,CLIP_MAX_ZOOM,clipCovers,DEFAULT_BACKGROUND,@@ -984,6 +987,49 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {};},+ detect_beats: async (s, input) => {+ const { asset, clip, speed, from, to } = resolveWatchRange(s, input);+ if (assetIsSilent(asset)) throw new ToolError(`"${asset.name}" carries no audio.`);+ // A stored grid holds the user's hand edits, so it answers as it stands;+ // regenerate re-scans the source and replaces it. A source a scan has+ // already read and heard nothing in answers empty without scanning+ // again — asking about three clips of one interview is one scan.+ const stored = asset.beats;+ const known = stored ?? (beatlessFor(asset.id) ? { beats: [], bpm: 0 } : null);+ const grid =+ known && input.regenerate !== true+ ? known+ : await detectAssetBeats(asset).catch((e) => {+ throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");+ });+ const beats = grid.beats.filter((b) => b >= from && (to === undefined || b <= to));+ const toTimeline = (t: number) => round2(clip!.start + (t - clip!.in) / speed);+ return {+ bpm: grid.bpm,+ beats: beats.map(round2),+ ...(clip+ ? {+ timelineBeats: grid.beats.filter((b) => b >= clip.in && b <= clip.out).map(toTimeline),+ clip: {+ id: clip.id,+ timelineStart: round2(clip.start),+ in: round2(clip.in),+ out: round2(clip.out),+ speed: round2(speed),+ },+ }+ : {}),+ source: { assetId: asset.id, name: asset.name, duration: round2(asset.duration) },+ note:+ grid.beats.length === 0+ ? "No steady pulse heard — the source reads as speech or ambience. The user can place beats by hand (⌥-click the clip bar)."+ : "The grid lives on the asset: its clips draw the beats as dots and every drag or trim snaps to them." ++ (stored && input.regenerate !== true+ ? " This is the stored grid, the user's hand edits included; pass regenerate to re-scan."+ : ""),+ };+ },+listen_audio: async (s, input) => {const { projectId, asset, clip, from, to } = resolveWatchRange(s, input);if (asset.type === "image")@@ -3373,6 +3419,7 @@ export const MEDIA_RUNTIME_TOOLS: ReadonlySet<string> = new Set(["watch_video","listen_audio","detect_silence",+ "detect_beats","refine_speech_cuts","capture_frame","freeze_frame",diff --git a/site/src/cut/lib/audioScan.test.ts b/site/src/cut/lib/audioScan.test.tsindex d9186627..27204d61 100644--- a/site/src/cut/lib/audioScan.test.ts+++ b/site/src/cut/lib/audioScan.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from "bun:test";-import { scanSilence, scanSpeech, type PcmChunk } from "./audioScan";+import { scanBeats, scanSilence, scanSpeech, type PcmChunk } from "./audioScan";const RATE = 8000;@@ -214,3 +214,130 @@ describe("scanSpeech", () => {expect(part.segments[0].end).toBeCloseTo(last.end, 1);});});++/** A percussive track: 20ms tone bursts every `period` seconds over silence. */+function clickTrack(seconds: number, period: number, first = 0.5): Float32Array {+ const data = new Float32Array(Math.round(seconds * RATE));+ const burst = Math.round(0.02 * RATE);+ for (let t = first; t < seconds - 0.05; t += period) {+ const start = Math.round(t * RATE);+ for (let i = 0; i < burst && start + i < data.length; i++) {+ data[start + i] = 0.9 * Math.sin((2 * Math.PI * 1000 * i) / RATE);+ }+ }+ return data;+}++/** Feed `data` as mono chunks split every `every` seconds, timestamped from `at`. */+async function* beatPcm(data: Float32Array, every = 1, at = 0): AsyncGenerator<PcmChunk> {+ const per = Math.round(every * RATE);+ for (let start = 0; start < data.length; start += per) {+ yield {+ channels: [data.subarray(start, Math.min(data.length, start + per))],+ timestamp: at + start / RATE,+ sampleRate: RATE,+ };+ }+}++/** How far each beat sits from its nearest click, worst case. */+function worstMiss(beats: number[], seconds: number, period: number, first = 0.5): number {+ const clicks: number[] = [];+ for (let t = first; t < seconds - 0.05; t += period) clicks.push(t);+ return Math.max(...beats.map((b) => Math.min(...clicks.map((c) => Math.abs(b - c)))));+}++describe("scanBeats", () => {+ test("locks onto a 120 BPM click track", async () => {+ const found = await scanBeats(beatPcm(clickTrack(12, 0.5)));+ expect(Math.abs(found.bpm - 120)).toBeLessThan(4);+ expect(found.beats.length).toBeGreaterThan(17);+ expect(worstMiss(found.beats, 12, 0.5)).toBeLessThan(0.04);+ });++ test("locks onto a slower pulse", async () => {+ const period = 60 / 90;+ const found = await scanBeats(beatPcm(clickTrack(14, period)));+ expect(Math.abs(found.bpm - 90)).toBeLessThan(4);+ expect(worstMiss(found.beats, 14, period)).toBeLessThan(0.04);+ });++ test("hears no beats in a steady tone", async () => {+ const data = new Float32Array(8 * RATE);+ for (let i = 0; i < data.length; i++) data[i] = 0.5 * Math.sin((2 * Math.PI * 440 * i) / RATE);+ expect((await scanBeats(beatPcm(data))).beats).toEqual([]);+ });++ test("hears no beats in silence", async () => {+ expect((await scanBeats(beatPcm(new Float32Array(8 * RATE)))).beats).toEqual([]);+ });++ test("reads the same grid however the chunks are split", async () => {+ const data = clickTrack(12, 0.5);+ const whole = await scanBeats(beatPcm(data, 12));+ const split = await scanBeats(beatPcm(data, 0.7));+ expect(split.beats).toEqual(whole.beats);+ expect(split.bpm).toBe(whole.bpm);+ });++ test("keeps beats in absolute source seconds", async () => {+ const found = await scanBeats(beatPcm(clickTrack(12, 0.5), 1, 3));+ expect(found.beats[0]).toBeGreaterThan(3);+ const shifted = found.beats.map((b) => b - 3);+ expect(worstMiss(shifted, 12, 0.5)).toBeLessThan(0.04);+ });+});++/** Clicks at the given moments, over an optional noise floor (amplitude). */+function clicksAt(times: number[], seconds: number, noise = 0): Float32Array {+ const data = new Float32Array(Math.round(seconds * RATE));+ if (noise > 0) {+ const r = rng(11);+ for (let i = 0; i < data.length; i++) data[i] = r() * noise * 2;+ }+ const burst = Math.round(0.02 * RATE);+ for (const t of times) {+ const start = Math.round(t * RATE);+ for (let i = 0; i < burst && start + i < data.length; i++)+ data[start + i] += 0.9 * Math.sin((2 * Math.PI * 1000 * i) / RATE);+ }+ return data;+}++/** How far each detected beat sits from its nearest click, worst case. */+const missVs = (beats: number[], clicks: number[]) =>+ Math.max(...beats.map((b) => Math.min(...clicks.map((c) => Math.abs(b - c)))));++describe("scanBeats under real-world conditions", () => {+ test("follows a player who speeds up", async () => {+ // The pulse tightens from 0.54s to 0.46s across the take — a fixed grid+ // at the average tempo would land ~40ms off by the ends.+ const times: number[] = [];+ for (let t = 0.5; t < 13.5; t += 0.54 - 0.08 * (t / 14)) times.push(t);+ const found = await scanBeats(beatPcm(clicksAt(times, 14)));+ expect(found.beats.length).toBeGreaterThan(20);+ expect(missVs(found.beats, times)).toBeLessThan(0.05);+ });++ test("hears the pulse through a noise bed", async () => {+ const times: number[] = [];+ for (let t = 0.5; t < 11.5; t += 0.5) times.push(t);+ const found = await scanBeats(beatPcm(clicksAt(times, 12, 0.03)));+ expect(Math.abs(found.bpm - 120)).toBeLessThan(4);+ expect(missVs(found.beats, times)).toBeLessThan(0.04);+ });++ test("holds the grid across a rest", async () => {+ // Three hits sit out mid-track. The grid keeps time through the rest —+ // that is what a rest is — so the check is that every played hit still+ // has a beat on it, at the played tempo.+ const times: number[] = [];+ for (let t = 0.5; t < 13.5; t += 0.5) times.push(t);+ const played = times.filter((t) => t < 6 || t > 7.6);+ const found = await scanBeats(beatPcm(clicksAt(played, 14)));+ expect(Math.abs(found.bpm - 120)).toBeLessThan(4);+ for (const c of played) {+ expect(Math.min(...found.beats.map((b) => Math.abs(b - c)))).toBeLessThan(0.045);+ }+ });+});diff --git a/site/src/cut/lib/audioScan.ts b/site/src/cut/lib/audioScan.tsindex d83856b8..f39fa1d7 100644--- a/site/src/cut/lib/audioScan.ts+++ b/site/src/cut/lib/audioScan.ts@@ -327,3 +327,314 @@ export async function scanSpeech(const env = await scanEnvelope(chunks, { ...opts, hop: SPEECH_HOP });return speechFrom(env);}++/** A source's musical beat grid. */+export interface BeatScan {+ /** Beat moments in source seconds, ascending. */+ beats: number[];+ /** Tempo of the grid, beats per minute; 0 when no steady pulse was heard. */+ bpm: number;+}++// The beat scan hears music the way the level fold cannot: a bass drop or a+// synth swell moves the RMS while the pulse hides inside it. So the fold here+// is spectral — each analysis window becomes a magnitude spectrum, and an+// onset is the frame where energy APPEARS across bins (half-wave rectified+// spectral flux on log magnitudes). Tempo is the onset train's strongest+// periodicity, and the beats themselves come from a dynamic program that+// walks the onsets at that period while giving a little to follow the player.++/** Analysis window, seconds. Rounded to a power of two of the stream's rate. */+const BEAT_WIN_S = 0.046;+/** The highest rate the beat scan analyzes at. Onsets live in spectral flux a+ * few kHz up at most, so a source above this folds down to it: the window+ * shrinks with the rate and the arithmetic inside each FFT with it, while the+ * hop stays the same slice of time — the grid keeps its accuracy and a long+ * file costs a fraction of what a full-rate scan would. A source already+ * below it is read as it is; resampling upward would only invent detail. */+const BEAT_RATE = 11025;+/** Log compression of the magnitudes, so quiet hits register beside loud ones. */+const FLUX_GAMMA = 100;+/** The local-mean window that turns flux into onsets, seconds each side. */+const FLUX_MEAN_S = 0.5;+/** Tempo prior: a pulse near 120 BPM is the likeliest read... */+const TEMPO_CENTER_S = 0.5;+/** ...with an octave of width either way. */+const TEMPO_WIDTH_OCT = 1.0;+/** Fastest tempo considered — 240 BPM. */+const TEMPO_MIN_S = 0.25;+/** Slowest tempo considered — 50 BPM. */+const TEMPO_MAX_S = 1.2;+/** Onset autocorrelation under this share of the train's energy is no pulse. */+const MIN_PERIODICITY = 0.1;+/** Onsets under this per-bin flux are the numeric floor — a steady tone's+ * leakage ripple beats against the hop grid periodically, and real music sits+ * orders of magnitude above it. */+const MIN_ONSET_LEVEL = 0.01;+/** How hard the tracker holds the tempo against the onsets' pull. */+const TIGHTNESS = 100;+/** A grid needs at least this many beats to be one. */+const MIN_BEATS = 4;+/** An edge beat holds only with onset energy under it, so the grid stops+ * where the music does: at least this much on the rms-normalized envelope... */+const EDGE_SUPPORT = 0.1;+/** ...and at least this share of the median beat's — a noise floor sits well+ * under the hits however the normalization landed. */+const EDGE_SHARE = 0.2;++/** In-place radix-2 FFT over split re/im arrays (length a power of two). */+function fft(re: Float32Array, im: Float32Array) {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i++) {+ let bit = n >> 1;+ for (; j & bit; bit >>= 1) j ^= bit;+ j |= bit;+ if (i < j) {+ const tr = re[i];+ re[i] = re[j];+ re[j] = tr;+ const ti = im[i];+ im[i] = im[j];+ im[j] = ti;+ }+ }+ for (let len = 2; len <= n; len <<= 1) {+ const ang = (-2 * Math.PI) / len;+ const wr = Math.cos(ang);+ const wi = Math.sin(ang);+ for (let i = 0; i < n; i += len) {+ let cr = 1;+ let ci = 0;+ for (let k = 0; k < len / 2; k++) {+ const a = i + k;+ const b = a + len / 2;+ const xr = re[b] * cr - im[b] * ci;+ const xi = re[b] * ci + im[b] * cr;+ re[b] = re[a] - xr;+ im[b] = im[a] - xi;+ re[a] += xr;+ im[a] += xi;+ const nr = cr * wr - ci * wi;+ ci = cr * wi + ci * wr;+ cr = nr;+ }+ }+ }+}++/**+ * The beat grid behind an onset envelope: tempo by autocorrelation under a+ * log-Gaussian prior, then beat placement by dynamic programming — each frame+ * either extends a chain one period back (give or take, at a log-time cost)+ * or starts fresh, and the best-scoring chain is the grid. `t0` is the source+ * second of frame 0, `hopSec` the frame width.+ */+export function beatsFromOnsets(flux: Float32Array, hopSec: number, t0: number): BeatScan {+ const n = flux.length;+ const none: BeatScan = { beats: [], bpm: 0 };+ if (n * hopSec < 2) return none;++ // Onset strength: flux over its local mean, so a swell carries no onsets+ // and a hit in a quiet bar counts beside one in a loud chorus.+ const half = Math.max(1, Math.round(FLUX_MEAN_S / hopSec));+ const prefix = new Float64Array(n + 1);+ for (let i = 0; i < n; i++) prefix[i + 1] = prefix[i] + flux[i];+ const o = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ const a = Math.max(0, i - half);+ const b = Math.min(n, i + half + 1);+ o[i] = Math.max(0, flux[i] - (prefix[b] - prefix[a]) / (b - a));+ }+ let sq = 0;+ for (let i = 0; i < n; i++) sq += o[i] * o[i];+ const rms = Math.sqrt(sq / n);+ if (rms < MIN_ONSET_LEVEL) return none;+ for (let i = 0; i < n; i++) o[i] /= rms;++ // Tempo: the onset train's autocorrelation, weighted toward middle tempi.+ const lagMin = Math.max(1, Math.round(TEMPO_MIN_S / hopSec));+ const lagMax = Math.min(n - 1, Math.round(TEMPO_MAX_S / hopSec));+ if (lagMax <= lagMin) return none;+ const score = new Float64Array(lagMax + 1);+ let bestLag = 0;+ let periodicity = 0;+ for (let lag = lagMin; lag <= lagMax; lag++) {+ let r = 0;+ for (let i = 0; i + lag < n; i++) r += o[i] * o[i + lag];+ r /= n - lag;+ const oct = Math.log2((lag * hopSec) / TEMPO_CENTER_S) / TEMPO_WIDTH_OCT;+ score[lag] = r * Math.exp(-0.5 * oct * oct);+ if (bestLag === 0 || score[lag] > score[bestLag]) {+ bestLag = lag;+ periodicity = r;+ }+ }+ // The envelope is rms-normalized, so its per-frame energy is 1 and the raw+ // autocorrelation reads directly as a share of it.+ if (periodicity < MIN_PERIODICITY) return none;+ let period = bestLag;+ if (bestLag > lagMin && bestLag < lagMax) {+ const y0 = score[bestLag - 1];+ const y1 = score[bestLag];+ const y2 = score[bestLag + 1];+ const d = y0 - 2 * y1 + y2;+ if (d < 0) period = bestLag + (0.5 * (y0 - y2)) / d;+ }++ // Beat placement: chain onsets a period apart, log-time cost on the slack.+ const winLo = Math.max(1, Math.round(period / 2));+ const winHi = Math.round(period * 2);+ const cum = new Float64Array(n);+ const back = new Int32Array(n).fill(-1);+ for (let i = 0; i < n; i++) {+ let bestS = 0;+ let bestJ = -1;+ for (let j = Math.max(0, i - winHi); j <= i - winLo; j++) {+ const slack = Math.log((i - j) / period);+ const s = cum[j] - TIGHTNESS * slack * slack;+ if (s > bestS) {+ bestS = s;+ bestJ = j;+ }+ }+ cum[i] = o[i] + (bestJ >= 0 ? bestS : 0);+ back[i] = bestJ;+ }+ let end = 0;+ for (let i = 1; i < n; i++) if (cum[i] > cum[end]) end = i;+ const idx: number[] = [];+ for (let i = end; i >= 0; i = back[i]) idx.push(i);+ idx.reverse();++ // The chain drifts on through leading and trailing quiet at pure penalty;+ // drop edge beats with nothing under them, so the grid spans the music.+ const support = (k: number) => {+ let m = 0;+ for (let j = Math.max(0, k - 2); j <= Math.min(n - 1, k + 2); j++) m = Math.max(m, o[j]);+ return m;+ };+ const supports = idx.map(support);+ const median = supports.slice().sort((a, b) => a - b)[Math.floor(supports.length / 2)] ?? 0;+ const floor = Math.max(EDGE_SUPPORT, EDGE_SHARE * median);+ let lo = 0;+ let hi = idx.length;+ while (lo < hi && supports[lo] < floor) lo++;+ while (hi > lo && supports[hi - 1] < floor) hi--;+ const kept = idx.slice(lo, hi);+ if (kept.length < MIN_BEATS) return none;++ return {+ beats: kept.map((k) => round3(t0 + k * hopSec)),+ bpm: Math.round((60 / (period * hopSec)) * 10) / 10,+ };+}++/**+ * The beat grid in `chunks`, in absolute source seconds.+ *+ * Everything runs on one fixed analysis grid at BEAT_RATE: each chunk is+ * folded down to it as it arrives, so a source whose decoder answers with a+ * different sample rate partway through still lands every sample in the right+ * place, and an hour-long file costs the frames its length deserves rather+ * than the frames its sample rate would buy.+ */+export async function scanBeats(chunks: AsyncIterable<PcmChunk>): Promise<BeatScan> {+ // The analysis rate is settled by the first chunk and holds for the scan.+ // The grid it defines is in absolute source time, so a later chunk arriving+ // at a different rate still folds onto it in the right place.+ let ar = 0;+ let win = 0;+ let hop = 0;+ let ring = new Float32Array(0);+ let hann = new Float32Array(0);+ let re = new Float32Array(0);+ let im = new Float32Array(0);+ let prev = new Float32Array(0);+ const flux: number[] = [];+ let base0 = -1;+ let filled = 0;++ const frame = () => {+ for (let i = 0; i < win; i++) {+ re[i] = ring[(filled - win + i) % win] * hann[i];+ im[i] = 0;+ }+ fft(re, im);+ let f = 0;+ for (let k = 1; k < win / 2; k++) {+ const m = Math.log1p(FLUX_GAMMA * Math.sqrt(re[k] * re[k] + im[k] * im[k]));+ const d = m - prev[k];+ if (d > 0) f += d;+ prev[k] = m;+ }+ // Per bin, so the envelope reads the same at every sample rate — and the+ // first window, with nothing behind it, reads as zero by definition.+ flux.push(flux.length === 0 && filled === win ? 0 : f / (win >> 1));+ };++ const push = (v: number) => {+ ring[filled % win] = v;+ filled++;+ if (filled >= win && (filled - win) % hop === 0) frame();+ };++ // The analysis sample being folded: every source sample landing on it+ // averages in, so decimating a 48 kHz file never drops a transient between+ // the samples it keeps.+ let foldAt = NaN;+ let foldSum = 0;+ let foldN = 0;+ const fold = () => {+ if (foldN === 0) return;+ const v = foldSum / foldN;+ foldSum = 0;+ foldN = 0;+ const at = foldAt - base0;+ if (at < filled) return; // already covered — chunks that overlap+ // A step up in rate (or a hole in the stream) holds the level rather than+ // dropping to zero, so the fill itself reads as no onset at all.+ while (filled < at) push(v);+ push(v);+ };++ for await (const { channels, timestamp, sampleRate } of chunks) {+ if (channels.length === 0 || channels[0].length === 0) continue;+ if (!(sampleRate > 0)) continue;+ if (ar === 0) {+ ar = Math.min(BEAT_RATE, sampleRate);+ win = 1 << Math.round(Math.log2(BEAT_WIN_S * ar));+ hop = win >> 2;+ ring = new Float32Array(win);+ re = new Float32Array(win);+ im = new Float32Array(win);+ prev = new Float32Array(win / 2);+ hann = new Float32Array(win);+ for (let i = 0; i < win; i++) hann[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / win);+ }+ const length = channels[0].length;+ const step = ar / sampleRate;+ // Sample positions rebuild from an index on the analysis grid, so neither+ // a chunk split nor a change of sample rate can move the frame grid+ // (scanEnvelope does the same).+ const base = timestamp * ar;+ for (let i = 0; i < length; i++) {+ const at = Math.floor(base + i * step);+ if (at !== foldAt) {+ fold();+ foldAt = at;+ if (base0 < 0) base0 = at;+ }+ let v = 0;+ for (const ch of channels) v += ch[i];+ foldSum += v / channels.length;+ foldN++;+ }+ }+ fold();+ if (ar === 0 || flux.length === 0) return { beats: [], bpm: 0 };++ // A frame's flux belongs to the hop of samples that entered the window for+ // it; its moment is the middle of that hop.+ const t0 = (base0 + win - hop / 2) / ar;+ return beatsFromOnsets(Float32Array.from(flux), hop / ar, t0);+}diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.tsindex d1f25fcb..ba9665a7 100644--- a/site/src/cut/lib/laneTracks.ts+++ b/site/src/cut/lib/laneTracks.ts@@ -105,6 +105,9 @@ interface LaneAdapter<T> {lanePatch?(raw: T, lane: number): Patch<T>;/** The media behind the item, so dragging it can feed reference drop zones. */assetOf?(s: S, raw: T): MediaAsset | undefined;+ /** The asset's beat grid mapped through this item onto the timeline —+ * snap targets, so an edge lands on the music. Media kinds only. */+ beatTimes?(s: S, raw: T): number[];/** A lifted item's slot closes behind it: while one drags, same-lane items* past its old spot rest slid left by its length, so the run heals the* moment the item leaves. Video tracks set this; free-form lanes (audio,@@ -119,6 +122,21 @@ interface LaneAdapter<T> {const speedOf = (c: { speed?: number }) => (c.speed && c.speed > 0 ? c.speed : 1);+/** The asset's beats inside a media item's trimmed range, in timeline+ * seconds. Beats live on the asset in source seconds, so every clip showing+ * the source maps its own window of them. */+function mediaBeatTimes(+ s: S,+ c: { assetId: string; start: number; in: number; out: number; speed?: number }+): number[] {+ const beats = s.assets.find((a) => a.id === c.assetId)?.beats?.beats;+ if (!beats?.length) return [];+ const speed = speedOf(c);+ const times: number[] = [];+ for (const b of beats) if (b >= c.in && b <= c.out) times.push(c.start + (b - c.in) / speed);+ return times;+}+function videoMaxLen(s: S, c: VideoClip): number {const a = s.assets.find((x) => x.id === c.assetId);// A still has no source length, so its clip can stretch to any duration.@@ -150,7 +168,9 @@ const clipAdapter: LaneAdapter<VideoClip> = {leftFloor: (c) => Math.max(0, c.start - c.in / speedOf(c)),maxLen: videoMaxLen,closesGap: true,- assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId), onMoved: () => useEditor.getState().sortClips(),+ assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),+ beatTimes: mediaBeatTimes,+ onMoved: () => useEditor.getState().sortClips(),};const audioAdapter: LaneAdapter<AudioClip> = {@@ -176,7 +196,9 @@ const audioAdapter: LaneAdapter<AudioClip> = {maxLen: (s, a) =>((s.assets.find((x) => x.id === a.assetId)?.duration ?? a.out) - a.in) / speedOf(a),lanePatch: (a, lane) => ({ id: a.id, patch: { lane: lane > 0 ? lane : undefined } }),- assetOf: (s, a) => s.assets.find((x) => x.id === a.assetId),};+ assetOf: (s, a) => s.assets.find((x) => x.id === a.assetId),+ beatTimes: mediaBeatTimes,+};const textAdapter: LaneAdapter<Overlay> = {minLen: 0.2,@@ -217,7 +239,9 @@ const overlayClipAdapter: LaneAdapter<VideoClip> = {leftFloor: (c) => Math.max(0, c.start - c.in / speedOf(c)),maxLen: videoMaxLen,closesGap: true,- assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),};+ assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),+ beatTimes: mediaBeatTimes,+};const cueAdapter: LaneAdapter<SubtitleCue> = {minLen: 0.15,@@ -256,15 +280,26 @@ const ADAPTERS: Record<LaneKind, LaneAdapter<LaneRaw>> = {};/** Logical times an edge can snap to: the timeline start, video track 0's- * cut points and end, the playhead, and every other lane item's edges across- * all track kinds — a title can align to a music hit and vice versa. */-function snapTargets(s: S, kind: LaneKind, selfId: string): number[] {- return snapTargetsExcluding(s, new Set([`${structureOf(kind)}:${selfId}`]));+ * cut points and end, the playhead, every other lane item's edges across all+ * track kinds, and every beat of an asset's detected grid mapped through its+ * clips — a title can align to a music hit and vice versa. */+function snapTargets(s: S, kind: LaneKind, selfId: string, ownBeats = false): number[] {+ return snapTargetsExcluding(s, new Set([`${structureOf(kind)}:${selfId}`]), ownBeats);}/** Snap targets with a whole set of items excluded — a group drag must not- * snap the moving set against its own edges. Keys are `structure:id`. */-function snapTargetsExcluding(s: S, excluded: ReadonlySet<string>): number[] {+ * snap the moving set against its own edges. Keys are `structure:id`.+ *+ * `ownBeats` keeps the excluded items' beat grids as targets, which is what a+ * trim wants: neither edge moves the source under the bar, so the item's own+ * beats hold still while the edge travels and landing an edit on the music+ * means landing on one of them. A move carries the source along, so there the+ * grid travels with the item and only everything else's beats are targets. */+function snapTargetsExcluding(+ s: S,+ excluded: ReadonlySet<string>,+ ownBeats = false+): number[] {const pts = new Set<number>([0]);for (const sp of getClipSpans(s.clips, s.assets)) {// The joint: every pair meets at the footprint end — a transition is a@@ -276,9 +311,12 @@ function snapTargetsExcluding(s: S, excluded: ReadonlySet<string>): number[] {for (const k of Object.keys(ADAPTERS) as LaneKind[]) {for (const raw of ADAPTERS[k].raws(s)) {const v = ADAPTERS[k].view(raw);- if (excluded.has(`${structureOf(k)}:${v.id}`)) continue;- pts.add(v.start);- pts.add(v.start + v.len);+ const self = excluded.has(`${structureOf(k)}:${v.id}`);+ if (!self) {+ pts.add(v.start);+ pts.add(v.start + v.len);+ }+ if (!self || ownBeats) for (const t of ADAPTERS[k].beatTimes?.(s, raw) ?? []) pts.add(t);}}return [...pts];@@ -1141,7 +1179,9 @@ export function startLaneTrim(// Grabbing an edge pauses playback so the trim isn't fighting a moving playhead.if (s.playing) s.setPlaying(false);s.pushHistory();- const targets = snapTargets(s, kind, id);+ // A trim leaves the source where it is, so this item's own beats are targets+ // like any other: "cut on the beat" is the whole point of the grid.+ const targets = snapTargets(s, kind, id, true);const tol = SNAP_PX / ui.pps;const sameLane = ad.raws(s)diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex d3ddcf85..1849b2b9 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -1,6 +1,6 @@"use client";-import { scanSilence, scanSpeech, type PcmChunk, type SpeechScan } from "./audioScan";+import { scanBeats, scanSilence, scanSpeech, type BeatScan, type PcmChunk, type SpeechScan } from "./audioScan";import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";import { cloudBackend } from "./backend/cloud";import { pollCloudJob } from "./cloudJob";@@ -44,7 +44,7 @@ import {import { pickThumbTimes, type ThumbProbe } from "./filmstrip";import { reportSwallowed } from "./report";import { useEditor } from "./store";-import type { AssetType, AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip, WatchKeepReason } from "./types";+import type { AssetBeats, AssetType, AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip, WatchKeepReason } from "./types";import { contentRect, IMAGE_CLIP_SECONDS, mediaUrl } from "./types";import { createDedupSelector, DEDUP_TUNING } from "./watch/dedupSelector";import { diffCellPct, frameSig } from "./watch/signatures";@@ -1101,6 +1101,15 @@ export async function scanSourceSpeech(return scanSpeech(sourcePcm(sourceUrl, from, opts.to), { ...opts, from });}+/** The source's musical beat grid, end to end. The grid is a property of the+ * whole file — tempo tracking needs the run of it — so a scan always reads+ * everything; callers window the result. Same residency story as the speech+ * scan: the page decodes its own media, the headless runner installs the+ * same decoders. */+export async function scanSourceBeats(sourceUrl: string): Promise<BeatScan> {+ return scanBeats(sourcePcm(sourceUrl, 0, undefined));+}+/** Cloud twin of the engine's audio-extract route: render a span of the* source's audio to 16 kHz mono WAV in the browser, for the AI to hear* inline. An empty `to` runs to the end. */@@ -1568,6 +1577,59 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {}}+// Beat scans in flight, by asset id — session state. The clip menu reads it+// to show the scan running, and a second ask joins the first's promise.+const beatScans = new Map<string, Promise<AssetBeats>>();+// Sources a scan has already read and found no steady pulse in. Nothing lands+// on the asset in that case — an empty grid is no grid — so without this a+// caller that only wants the stored grid would pay for the whole scan again+// every time it asked about a speech recording.+const beatlessScans = new Set<string>();+const beatListeners = new Set<() => void>();++export function subscribeBeatsBusy(fn: () => void) {+ beatListeners.add(fn);+ return () => {+ beatListeners.delete(fn);+ };+}++/** Whether a beat scan is running for this asset. */+export const beatsBusyFor = (assetId: string) => beatScans.has(assetId);++/** Whether a scan has already read this source and heard no pulse. A caller+ * reading the stored grid uses it to tell "never scanned" from "scanned, no+ * beats" — the second needs no second scan. A re-scan clears it. */+export const beatlessFor = (assetId: string) => beatlessScans.has(assetId);++/**+ * Detect the source's beat grid and write it onto the asset (types.ts+ * AssetBeats): its clips draw the beats as dots and every drag or trim snaps+ * to them. Replaces whatever grid was there — detection is the starting+ * point, the dots are the user's to edit from there. A scan that hears no+ * steady pulse clears the grid and returns the empty scan.+ */+export async function detectAssetBeats(asset: MediaAsset): Promise<AssetBeats> {+ const running = beatScans.get(asset.id);+ if (running) return running;+ const scan = (async () => {+ const { beats, bpm } = await scanSourceBeats(asset.url);+ const grid = { beats, bpm };+ useEditor.getState().updateAsset(asset.id, { beats: beats.length ? grid : undefined });+ if (beats.length) beatlessScans.delete(asset.id);+ else beatlessScans.add(asset.id);+ return grid;+ })();+ beatScans.set(asset.id, scan);+ for (const fn of beatListeners) fn();+ try {+ return await scan;+ } finally {+ beatScans.delete(asset.id);+ for (const fn of beatListeners) fn();+ }+}+/** Waveform peaks on demand — e.g. when a video clip's audio is detached* onto the soundtrack track (video assets don't get peaks at import). */export async function ensurePeaks(asset: MediaAsset) {diff --git a/site/src/cut/lib/pi/mutationLedger.ts b/site/src/cut/lib/pi/mutationLedger.tsindex 7e505a5d..cbc5e242 100644--- a/site/src/cut/lib/pi/mutationLedger.ts+++ b/site/src/cut/lib/pi/mutationLedger.ts@@ -14,6 +14,7 @@ const READ_ONLY = new Set(["watch_video","note_source","detect_silence",+ "detect_beats","listen_audio","read_color_stats","library_list",diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 0aab81f9..d7bad457 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -16,6 +16,7 @@ import {import { create } from "zustand";import type {Aspect,+ AssetBeats,AudioClip,ClipAnim,ClipSpan,@@ -216,6 +217,11 @@ interface DocSnapshot {audioClips: AudioClip[];overlays: Overlay[];subtitles: SubtitlesBlock;+ /** Each asset's beat grid. Beats are edited on the timeline like anything+ * else — dragged, added, removed, cleared — but they live on the asset+ * rather than in the doc arrays, so the checkpoint carries them separately+ * and the restore puts them back. */+ beats: { id: string; grid: AssetBeats | undefined }[];}export type SubtitleStatus = "idle" | "running" | "ready" | "empty" | "error";@@ -1334,8 +1340,9 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {api.setState = set as typeof api.setState;const snapshot = (): DocSnapshot => {- const { clips, transitions, audioClips, overlays, subtitles } = get();+ const { clips, transitions, audioClips, overlays, subtitles, assets } = get();return {+ beats: assets.map((a) => ({ id: a.id, grid: a.beats })),// Render-owned clips are excluded — history captures the user's timeline,// not the background run's placements (restoreDoc re-attaches the live ones).clips: clips.filter((c) => !genClipIds.has(c.id)).map((c) => ({ ...c })),@@ -1353,13 +1360,22 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {* an undo/redo never disturbs a background run's placements. The live gen* clips are read at restore time, so the set is always current. */const restoreDoc = (snap: DocSnapshot) => {- const { clips, audioClips } = get();+ const { beats, ...doc } = snap;+ const { clips, audioClips, assets } = get();const genClips = clips.filter((c) => genClipIds.has(c.id));const genAudio = audioClips.filter((c) => genAudioIds.has(c.id));+ // Beat grids go back onto the assets they came off. An asset imported+ // since the checkpoint was taken is not in it and keeps the grid it has.+ const grids = new Map(beats.map((b) => [b.id, b.grid]));+ const withBeats = assets.map((a) =>+ grids.has(a.id) && grids.get(a.id) !== a.beats ? { ...a, beats: grids.get(a.id) } : a+ );+ const beatsMoved = withBeats.some((a, i) => a !== assets[i]);set({- ...snap,- clips: [...snap.clips, ...genClips].sort((a, b) => a.start - b.start),- audioClips: [...snap.audioClips, ...genAudio],+ ...doc,+ clips: [...doc.clips, ...genClips].sort((a, b) => a.start - b.start),+ audioClips: [...doc.audioClips, ...genAudio],+ ...(beatsMoved ? { assets: withBeats } : {}),selection: null,multiSelection: [],});@@ -4688,15 +4704,27 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {};});+/** Whether any asset's beat grid was rewritten between two asset lists. An+ * asset arriving or leaving is no beat edit; only a grid changing under an id+ * that was already there counts. */+function beatsEdited(prev: MediaAsset[], next: MediaAsset[]): boolean {+ const before = new Map(prev.map((a) => [a.id, a.beats]));+ return next.some((a) => before.has(a.id) && before.get(a.id) !== a.beats);+}+// Track real edits to the persistable doc so a deferred checkpoint (see push)-// knows whether an edit actually happened between capture and commit.+// knows whether an edit actually happened between capture and commit. Beat+// grids ride on the assets, and an asset list churns for reasons that are no+// edit at all (peaks, filmstrips, re-signed URLs), so that one is read by+// what actually changed.useEditor.subscribe((s, prev) => {if (s.clips !== prev.clips ||s.transitions !== prev.transitions ||s.audioClips !== prev.audioClips ||s.overlays !== prev.overlays ||- s.subtitles !== prev.subtitles+ s.subtitles !== prev.subtitles ||+ (s.assets !== prev.assets && beatsEdited(prev.assets, s.assets)))docSeq++;});@@ -4767,7 +4795,7 @@ export const docOverlays = (() => {export function storedAssets(assets: MediaAsset[]): StoredAsset[] {return assets.filter((a) => !tabOnlyUpload(a))- .map(({ id, fileName, name, type, duration, width, height, origin, chatId, language, watch, speech }) => ({+ .map(({ id, fileName, name, type, duration, width, height, origin, chatId, language, watch, speech, beats }) => ({id,fileName,name,@@ -4780,6 +4808,7 @@ export function storedAssets(assets: MediaAsset[]): StoredAsset[] {...(language !== undefined ? { language } : {}),...(watch !== undefined ? { watch } : {}),...(speech !== undefined ? { speech } : {}),+ ...(beats !== undefined ? { beats } : {}),}));}diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex e26b5860..418bd2e7 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -163,6 +163,17 @@ export interface AssetSpeech {locale?: string;}+/** The source's musical beat grid, in source seconds. Detected from the+ * audio, then the user's to edit: the dots on a clip move, add, and delete+ * beats by hand. Same lifecycle as AssetSpeech: saves with the project, dies+ * with the asset, never stale (media files are immutable). */+export interface AssetBeats {+ /** Beat moments, ascending. */+ beats: number[];+ /** Tempo of the detected grid, BPM; 0 once the grid is hand-placed. */+ bpm: number;+}+export interface StoredAsset {id: string;fileName: string; // file inside the project's media/ folder@@ -175,6 +186,8 @@ export interface StoredAsset {watch?: AssetWatch;/** The source's own transcript — what the assistant has heard. */speech?: AssetSpeech;+ /** The music's beat grid — dots on the clip, snap targets for every edge. */+ beats?: AssetBeats;/** How this asset entered the project. Absent = the user imported it (drag,* drop, or upload), so it belongs in the Media panel. Any value marks media* Cut created or fetched — it lives where it was made (the timeline, adiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 5ac88d96..6408da73 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -137,6 +137,7 @@ Your eyes and ears:**Reading on-screen text.** Recreating a video's titles, captions or kinetic typography is a transcription job, so read every card in order with its own timing: watch the whole source at \`interval_seconds\` 0.5 (a line that builds a word at a time — "You" → "You know that building" → "is everything today" — is one card, and a 1s floor collapses or skips those steps), and write each card's text, its in/out, its color and its position into note_source as you read it — that record is what you build the cut from a turn later, when the sheets are gone. Copy the text exactly, including the lines you would have trimmed; a fragment placed as if it were a whole card ("I got half of" without "my clients from Linkedin last year") is a misquote of the user's reference. Cards frequently continue across cuts — before you decide a card is finished, check the next one for the rest of its sentence.- detect_silence(clip_id | asset_id, threshold_db?, min_silence?): silent stretches in source seconds; with clip_id each also carries its timeline times.+- detect_beats(clip_id | asset_id, regenerate?): the music's beat grid — bpm and beat times in source seconds, plus timelineBeats ready for split_at with clip_id. The grid persists on the asset, draws as yellow dots on its clips, and every drag or trim snaps to it. "Cut to the beat" / "sync to the music" means detect, then split or place at the timeline beat times; the stored grid carries the user's hand edits, so re-detect only when they ask.- capture_frame(t?): one composited frame, at the given time in seconds or the playhead — for checking the final look. Surveying footage is watch_video's job.The flow for "edit this for me":@@ -309,6 +310,7 @@ ${textMoveCatalog()}Lyrics and scripts the user already has: sync_lyrics times their exact words against the audio (transcribing first when needed) and writes them to a caption track with per-word timings; set_caption_look then dresses the track — preset, size, font, word effect, accent color — from a text-videos look id or field by field. The text-videos skill has the whole flow, including turning the same timed lines into full-frame cards.Soundtrack clips: volume 0..3 (1 = unchanged, above 1 boosts), fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source; clips can spread across several soundtrack lanes (the \`lane\` field), new sounds slide to free space in their lane. Fades render with ffmpeg afade on export.Ducking: a soundtrack clip's \`duck\` (0..1, via update_audio) lowers ALL other audio — video-clip sound and other music — to that gain while the clip plays; 1 clears it. Voiceovers set this so narration sits over quieter music. It applies in both the preview and the export.+Cutting to music: detect_beats reads a track's beat grid once — bpm plus every beat, with timeline times through the clip you pass — and the grid stays on the asset as yellow dots the user can drag, add (⌥-click the bar), or delete, with every drag and trim snapping to them. Land cuts, clip starts, and text entrances on those times: split_at at the timeline beats, or place each item to start on one.Audio effects (add_effect): the treatments over the sound — ${AUDIO_EFFECT_IDS.join(", ")} — placed on the timeline as elements, each treating everything audible under its window at once. Reach for one when the ask is how a stretch SOUNDS ("make this line sound like a phone call", "echo on that word", "muffle the music behind the voiceover"); \`amount\` says how far the treatment goes, and the effect trims and moves like any element. Loudness, fades and ducking on one clip stay with the audio tools; a dissolve across a cut stays with the transition on that cut (the audiocross style).Voiceover (Donkey's hosted speech model — signed in, spends credits, like image/video generation):- voiceover_generate(script, voice?, direction?, duck?, add_to_timeline?, start?, language?): synthesizes the script into a playable chat card; add_to_timeline:true (or a start) also drops it on the soundtrack at the playhead (or start) when the user asked for it in the cut. Defaults to a 0.4 duck when placed so it sits over other audio. Voices are Gemini's prebuilt set — list_voices returns them (id + one-word character like Warm, Upbeat, Gravelly); omit voice for a good default. \`direction\` steers delivery in natural language ("Say warmly, like an old friend") and may ask for another language — "say it in Spanish" translates the script before synthesis; the script itself can carry inline tags like [whispers], [excited], [laughs]. \`language\` only pins pronunciation of the text as written.@@ -390,7 +392,7 @@ Rules:- Transcription tools write tracks the user sees — run subtitles_generate / captions_generate only when captions were asked for, never just to read the words: existing cues are in editor_state, sources you have watched or listened to carry their own transcript (media entries marked speech: "transcribed"; get_state includes the timed segments), and audio plays to you via listen_audio. Don't transcribe a video with no speech (subtitles_from_visuals narrates silent footage), and never invent a spoken transcript.- Voiceovers duck other audio by default so they stay audible. Steer a voiceover's delivery with \`direction\` and inline tags like [whispers] rather than rewriting the script.- generate_image / generate_video / generate_character_video / voiceover_generate / read_subtitles_aloud / generate_music make media through hosted models (spends the user's Donkey credits, needs sign-in); call them when the user asked for the media itself — a request for the prompt or script gets text in chat. generate_music makes a music track — a vocal-free background bed by default ("add music to this video"), or a full sung song (instrumental:false); it's sung music, so a spoken narration is voiceover_generate. Bundled stock media (stock_search / stock_add) is free — use it when it fits. Media the user attached is in \`media\`; pass those asset ids as generation references when they say "use this", and place project assets in the cut with add_clip when they ask for them there ("make a movie from these photos"). Generated media previews on a chat card the user can expand, drag in, or file away; add it to the timeline (add_to_timeline:true or an index) only when they asked for it in the cut. When it lands on a card, close with a statement of where it is ("The voiceover is on the card — drag it in or tell me to place it."). Write a rich, specific prompt from their shorthand. Video renders take a minute or two. "Generate a video of/about X" means one generate_video clip; only when they name a narrated multi-shot production (a story, episode, narrated short) does generate_scene plan it and stop at the storyboard — the user reviews the frames (regenerate_shot redraws any before approval, no credits), then call approve_scene, since it renders many paid shots (regenerate_shot / recut_scene / restyle_scene revise it after). Close a plan message with the approval path as a statement: "Approve it — say so or hit Approve on the card — and I'll render the shots." Tweaks before approval are theirs to name.-- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen, and write each look down with note_source — sheets are conversation-local, notes stay on the source; listen_audio plays a source's audio — an audio asset or a video/clip's own track; detect_silence finds dead air; capture_frame shows one rendered frame, at the time you pass or the playhead. The watching-and-cutting skill has the flow.+- You can see and hear: audio the user attaches to their message plays right in it — answer "what does this say" from what you hear, no tool call. For project footage, watch_video samples a source's frames into timestamped contact sheets (scene changes included) — watch before cutting footage you haven't seen, and write each look down with note_source — sheets are conversation-local, notes stay on the source; listen_audio plays a source's audio — an audio asset or a video/clip's own track; detect_silence finds dead air; detect_beats reads the music's beat grid (persisted on the asset, drawn as dots on its clips, snapped to by every drag) for cutting to the music; capture_frame shows one rendered frame, at the time you pass or the playhead. The watching-and-cutting skill has the flow.- End on a statement. The final sentence of every reply states what changed, what failed, or the one suggestion you're making; "let me know if", "would you like", "do you want me to", and every other trailing offer or question are banned closers. The only question that may end a reply is the single clarifying one a genuinely ambiguous or blocked ask earns.`;}diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.tsindex 2f074d00..7a52e4e1 100644--- a/site/src/cut/server/ai/headlessTools.ts+++ b/site/src/cut/server/ai/headlessTools.ts@@ -23,6 +23,7 @@ const PAGE_MEDIA_TOOLS: ReadonlySet<string> = new Set(["watch_video","listen_audio","detect_silence",+ "detect_beats","refine_speech_cuts","freeze_frame","capture_frame",