Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): time a font cycle to the music's beats from the Inspector

David Le7862f8219b27
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 1229dd15..0581187a 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -118,6 +118,7 @@ import {
} from "@donkeycut/effects-kit";
import { SHADOW, SHADOW_BLUR_MAX, SHADOW_OFFSET_MAX, STRIPE_GAP_MAX, STRIPE_LINE_MAX, STRIPE_LINE_MIN, STRIPES_DEFAULT, type FlashPulse, type ShadowSpec, type StripesPattern } from "@donkeycut/effects-kit";
import { BLOCK_COLOR } from "@/cut/lib/blockSource";
+import { beatSwitches, clipBeatTimes, CYCLE_BEAT_STEPS, switchProblem, tidySwitches, timedFontCycle } from "@/cut/lib/fontCycleTiming";
import { bindRecording, unbindRecording } from "@/cut/lib/soundBind";
import { SPLIT_EDIT_MAX_S } from "@/cut/lib/soundSource";
import { clipLen, clipWindow, maxClipFade, useEditor, type EditorState } from "@/cut/lib/store";
@@ -3111,8 +3112,9 @@ function FontCycleFaces({ overlay: o, peers }: { overlay: TextOverlay; peers?: r
);
}
-/** Where the font cycle starts inside the title, how long it runs, and how
- * many times a second the face changes. */
+/** Where the font cycle starts inside the title, how long it runs, how
+ * many times a second the face changes, and the music beats that can time
+ * every face instead. */
function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: readonly Overlay[] }) {
const ck = useSliderCheckpoint();
const anim = o.anim ?? {};
@@ -3156,11 +3158,98 @@ function FontCycleSettings({ overlay: o, peers }: { overlay: Overlay; peers?: re
</Row>
);
const secs = (v: number) => `${v.toFixed(2)}s`;
+
+ // Clips whose music has a beat grid; one of them times every face.
+ const clips = useEditor((s) => s.clips);
+ const audioClips = useEditor((s) => s.audioClips);
+ const assets = useEditor((s) => s.assets);
+ const beatClips = useMemo(
+ () =>
+ [...audioClips, ...clips].flatMap((c) => {
+ const asset = assets.find((a) => a.id === c.assetId);
+ return (asset?.beats?.beats.length ?? 0) >= 2 ? [{ clip: c, asset: asset! }] : [];
+ }),
+ [clips, audioClips, assets]
+ );
+ const [fontCycleBeats, setFontCycleBeats] = useState<string>();
+ const [fontCycleBeatStep, setFontCycleBeatStep] = useState<number>(1);
+ const [beatNote, setBeatNote] = useState<string>();
+ const beatSource = beatClips.find((b) => b.clip.id === fontCycleBeats) ?? beatClips[0];
+
+ // A new face on each beat (or every other, or half beat) of the picked
+ // clip inside the cycle's run, the faces repeating to fill it.
+ const timeToBeats = () => {
+ if (!cycle || !beatSource) return;
+ const elDur = o.end - o.start;
+ const beats = clipBeatTimes(beatSource.clip, beatSource.asset).map((t) => t - o.start);
+ const edges = tidySwitches(
+ beatSwitches(beats, fontCycleBeatStep, fontCycleAt, fontCycleAt + fontCycleSeconds),
+ elDur
+ );
+ const problem = switchProblem(edges);
+ if (problem) {
+ setBeatNote(
+ problem.kind === "few"
+ ? "No beat of that clip lands inside the cycle."
+ : problem.kind === "many"
+ ? `That is ${problem.faces} face changes; a cycle holds ${FONT_CYCLE_FACES_MAX}. Pick a longer step.`
+ : `One face would hold ${problem.seconds.toFixed(2)}s, past the ${CYCLE_HOLD_MAX}s limit.`
+ );
+ return;
+ }
+ setBeatNote(undefined);
+ useEditor.getState().pushHistory();
+ writeOverlayAnim(o, anim, { fonts: timedFontCycle(cycle.faces, edges, fontCycleRate) }, peers);
+ };
+
return (
<>
{slider("At", fontCycleAt, 0, Math.max(0, dur - 0.05), 0.05, secs, "at")}
{slider("Duration", fontCycleSeconds, 0.05, Math.max(0.05, dur - fontCycleAt), 0.05, secs, "seconds")}
{slider("Rate", fontCycleRate, FONT_CYCLE_RATE_MIN, FONT_CYCLE_RATE_MAX, 1, (v) => `${Math.round(v)}/s`, "rate")}
+ <Row
+ label="Beats"
+ info="Time every face to the music: a new face on each beat of the picked clip inside the cycle, the faces repeating in order. Detect beats on the music clip first. Each face's Hold shows the result."
+ >
+ {beatClips.length === 0 ? (
+ <span className="text-[12px] text-muted-foreground">Detect beats on a clip</span>
+ ) : (
+ <div className="flex items-center gap-1.5">
+ <Select value={beatSource?.clip.id} onValueChange={(v) => setFontCycleBeats(String(v))} disabled={!cycle}>
+ <SelectTrigger className="h-8 w-24 text-[12px]">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {beatClips.map(({ clip, asset }) => (
+ <SelectItem key={clip.id} value={clip.id} className="text-[12px]">
+ {asset.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Select
+ value={String(fontCycleBeatStep)}
+ onValueChange={(v) => setFontCycleBeatStep(Number(v))}
+ disabled={!cycle}
+ >
+ <SelectTrigger className="h-8 w-16 text-[12px]" aria-label="Beats per face">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {CYCLE_BEAT_STEPS.map((step) => (
+ <SelectItem key={step} value={String(step)} className="text-[12px]">
+ {step === 0.5 ? "½ beat" : step === 1 ? "1 beat" : `${step} beats`}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button variant="secondary" size="sm" disabled={!cycle} onClick={timeToBeats}>
+ Time
+ </Button>
+ </div>
+ )}
+ </Row>
+ {beatNote && <p className="text-[11px] text-muted-foreground">{beatNote}</p>}
</>
);
}
diff --git a/site/src/cut/components/inspectorToolFields.test.ts b/site/src/cut/components/inspectorToolFields.test.ts
index e45f62d4..0a7a4480 100644
--- a/site/src/cut/components/inspectorToolFields.test.ts
+++ b/site/src/cut/components/inspectorToolFields.test.ts
@@ -142,6 +142,8 @@ const PANEL_NAME: Record<string, string> = {
profile: "clip-source-color",
// A caption's own spot is the cue panel's Own position switch.
follow_track: "setCuePosition",
+ // Switch times are written as each face's hold, the Hold slider per face.
+ font_cycle_switches: "hold",
};
/** The basic and detail grade sliders draw from the registries the tool's
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 53593566..f0c3afd5 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -123,6 +123,7 @@ import {
type TextWeight,
} from "@donkeycut/effects-kit";
import type { AiPanelToolName } from "@/cut/components/AiPanel.tools";
+import { beatSwitches, clipBeatTimes, switchProblem, tidySwitches, timedFontCycle, validBeatStep } from "./fontCycleTiming";
import { LOOP_SPEED_MAX, LOOP_SPEED_MIN, type OverlayAnimationToolName } from "@/cut/components/AnimationTiles.tools";
import type { AudioToolName } from "@/cut/components/AudioPanel.tools";
import type { CameraCardToolName } from "@/cut/components/CameraCardSection.tools";
@@ -7227,16 +7228,10 @@ function applyFontCycleInput(
const round = (v: number) => onFrame(Math.round(v * 1e6) / 1e6);
// Switch times (passed, or the beats of the music's clip) give each face
- // its own hold, the faces repeating in order to fill them. Example: faces
- // [a, b] over switches 2.5, 3, 4 on a title at 2 → a at 0.5 for 0.5s,
- // then b for 1s, and the title's own face after 4.
+ // its own hold, the faces repeating in order to fill them.
const edges = cycleSwitchesOf(s, o, input, at, seconds);
if (edges) {
- const timed = edges.slice(1).map((end, i) => ({
- ...faces[i % faces.length],
- hold: round(end - edges[i]),
- }));
- anim.fonts = { faces: timed, at: round(edges[0]), seconds: round(edges[edges.length - 1] - edges[0]), rate };
+ anim.fonts = timedFontCycle(faces, edges, rate, round);
return;
}
anim.fonts = { faces, at: round(at), seconds: round(seconds), rate };
@@ -7266,29 +7261,16 @@ function cycleSwitchesOf(
// Inside the element, in order; a switch under a face's shortest hold
// after the one before it merges into it, the run's end kept.
- const sorted = edges
- .filter((t) => t >= -1e-6 && t <= dur + 1e-6)
- .map((t) => Math.round(clamp(t, 0, dur) * 1e6) / 1e6)
- .sort((a, b) => a - b);
- edges = [];
- for (const t of sorted) {
- if (edges.length > 0 && t - edges[edges.length - 1] < CYCLE_HOLD_MIN) {
- if (t === sorted[sorted.length - 1] && edges.length > 1) {
- edges[edges.length - 1] = t;
- }
- continue;
- }
- edges.push(t);
- }
- if (edges.length < 2)
+ edges = tidySwitches(edges, dur);
+ const problem = switchProblem(edges);
+ if (problem?.kind === "few")
throw new ToolError("A timed font cycle needs at least two switch times inside the title: the first face's start and the last face's end.");
- if (edges.length - 1 > FONT_CYCLE_FACES_MAX)
+ if (problem?.kind === "many")
throw new ToolError(
- `That run changes face ${edges.length - 1} times; one cycle holds ${FONT_CYCLE_FACES_MAX}. Pass font_cycle_beat_step 2 (every other beat), or shorten the run with font_cycle_seconds.`
+ `That run changes face ${problem.faces} times; one cycle holds ${FONT_CYCLE_FACES_MAX}. Pass font_cycle_beat_step 2 (every other beat), or shorten the run with font_cycle_seconds.`
);
- const longest = Math.max(...edges.slice(1).map((t, i) => t - edges[i]));
- if (longest > CYCLE_HOLD_MAX)
- throw new ToolError(`One face would hold ${round2(longest)}s; a face holds at most ${CYCLE_HOLD_MAX}s. Add a switch inside that gap.`);
+ if (problem?.kind === "long")
+ throw new ToolError(`One face would hold ${round2(problem.seconds)}s; a face holds at most ${CYCLE_HOLD_MAX}s. Add a switch inside that gap.`);
return edges;
}
@@ -7311,31 +7293,13 @@ function beatSwitchesOf(
throw new ToolError(`"${asset?.name ?? clipId}" has no beat grid yet. Call detect_beats with clip_id ${clipId} first, then time the cycle to it.`);
// The beats the clip plays, on the element's clock, in play order.
- const retime = retimeOf(clip);
- const beats = grid
- .filter((b) => b >= clip.in && b <= clip.out)
- .map((b) => clip.start + retime.tAt(b) - elementStart)
- .sort((a, b) => a - b);
-
- // Every Nth beat counted from the run's first, or each beat split evenly.
+ const beats = clipBeatTimes(clip, asset).map((t) => t - elementStart);
const step = isNum(input.font_cycle_beat_step) && input.font_cycle_beat_step > 0 ? input.font_cycle_beat_step : 1;
- const whole = step >= 1 ? Math.round(step) : 1;
- const parts = step < 1 ? Math.round(1 / step) : 1;
- if (Math.abs((step >= 1 ? whole : 1 / parts) - step) > 1e-3)
+ if (!validBeatStep(step))
throw new ToolError("font_cycle_beat_step is a whole number of beats (1, 2, 4) or a split of one (0.5, 0.25).");
- const first = beats.findIndex((t) => t >= from - 1e-6);
- const picked = (first < 0 ? [] : beats.slice(first)).filter((_, i) => i % whole === 0);
- const points = picked.flatMap((b, i) =>
- i + 1 < picked.length ? Array.from({ length: parts }, (_, k) => b + ((picked[i + 1] - b) * k) / parts) : [b]
- );
-
- // The switches inside the run, closed by the next one or the run's end.
- const inside = points.filter((t) => t >= from - 1e-6 && t < to - 1e-6);
- if (inside.length === 0) throw new ToolError("No beat of that clip lands inside the cycle's run.");
- const after = points.find((t) => t >= to - 1e-6);
- const spacing = inside.length > 1 ? (inside[inside.length - 1] - inside[0]) / (inside.length - 1) : to - inside[0];
- const close = after !== undefined ? to : Math.min(to, inside[inside.length - 1] + spacing);
- return [...inside, close];
+ const switches = beatSwitches(beats, step, from, to);
+ if (switches.length === 0) throw new ToolError("No beat of that clip lands inside the cycle's run.");
+ return switches;
}
/** A font id the registry knows, or a refusal naming the one it does not. */
diff --git a/site/src/cut/lib/fontCycleTiming.test.ts b/site/src/cut/lib/fontCycleTiming.test.ts
new file mode 100644
index 00000000..a43b048d
--- /dev/null
+++ b/site/src/cut/lib/fontCycleTiming.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from "bun:test";
+import { beatSwitches, switchProblem, tidySwitches, timedFontCycle, validBeatStep } from "./fontCycleTiming";
+
+const beats = [0, 0.5, 1, 1.5, 2, 2.5, 3];
+
+describe("font cycle timing", () => {
+ test("every beat inside the run, closed by the run's end", () => {
+ expect(beatSwitches(beats, 1, 0.4, 2.2)).toEqual([0.5, 1, 1.5, 2, 2.2]);
+ });
+
+ test("every other beat counts from the run's first", () => {
+ expect(beatSwitches(beats, 2, 0.4, 2.2)).toEqual([0.5, 1.5, 2.2]);
+ });
+
+ test("half beats split each gap", () => {
+ expect(beatSwitches(beats, 0.5, 0.9, 2)).toEqual([1, 1.25, 1.5, 1.75, 2]);
+ });
+
+ test("no beat inside the run gives nothing", () => {
+ expect(beatSwitches(beats, 1, 3.1, 4)).toEqual([]);
+ });
+
+ test("a switch under a frame after the one before merges, the end kept", () => {
+ expect(tidySwitches([1, 0.5, 1.005, 2], 3)).toEqual([0.5, 1, 2]);
+ expect(tidySwitches([0.5, 1, 1.005], 3)).toEqual([0.5, 1.005]);
+ });
+
+ test("problems: too few, too many, too long", () => {
+ expect(switchProblem([1])).toEqual({ kind: "few" });
+ expect(switchProblem(Array.from({ length: 60 }, (_, i) => i * 0.1))?.kind).toBe("many");
+ expect(switchProblem([0, 11])).toEqual({ kind: "long", seconds: 11 });
+ expect(switchProblem([0, 1, 2])).toBeNull();
+ });
+
+ test("faces repeat in order over the gaps", () => {
+ const cycle = timedFontCycle([{ font: "A" }, { font: "B" }], [0.5, 1, 2, 2.5], 15);
+ expect(cycle).toEqual({
+ faces: [
+ { font: "A", hold: 0.5 },
+ { font: "B", hold: 1 },
+ { font: "A", hold: 0.5 },
+ ],
+ at: 0.5,
+ seconds: 2,
+ rate: 15,
+ });
+ });
+
+ test("beat steps are whole beats or even splits", () => {
+ expect([0.25, 0.5, 1, 2, 4].every(validBeatStep)).toBe(true);
+ expect([0, -1, 0.3, 1.5].some(validBeatStep)).toBe(false);
+ });
+});
diff --git a/site/src/cut/lib/fontCycleTiming.ts b/site/src/cut/lib/fontCycleTiming.ts
new file mode 100644
index 00000000..22b56fac
--- /dev/null
+++ b/site/src/cut/lib/fontCycleTiming.ts
@@ -0,0 +1,101 @@
+// A font cycle timed to switch points: the beats of a music clip, or times
+// read off a reference. The assistant's set_overlay_animation and the
+// Inspector's Font cycle panel both time a cycle through here, so a cycle
+// timed either way holds each face the same.
+
+import {
+ CYCLE_HOLD_MAX,
+ CYCLE_HOLD_MIN,
+ FONT_CYCLE_FACES_MAX,
+ retimeOf,
+ type CycleFace,
+ type OverlayFontCycle,
+} from "@donkeycut/effects-kit";
+import type { AudioClip, MediaAsset, VideoClip } from "./types";
+
+/** Beat steps the panel offers: half beats, every beat, every other, every fourth. */
+export const CYCLE_BEAT_STEPS = [0.5, 1, 2, 4] as const;
+
+/** The beats a clip plays, on the timeline's clock, in play order. Empty
+ * when the clip's asset has no beat grid yet. */
+export function clipBeatTimes(clip: VideoClip | AudioClip, asset: MediaAsset | undefined): number[] {
+ const grid = asset?.beats?.beats ?? [];
+ const retime = retimeOf(clip);
+ return grid
+ .filter((b) => b >= clip.in && b <= clip.out)
+ .map((b) => clip.start + retime.tAt(b))
+ .sort((a, b) => a - b);
+}
+
+/** Whether a beat step is whole beats (1, 2, 4) or an even split of one
+ * (0.5, 0.25). */
+export function validBeatStep(step: number): boolean {
+ if (!(step > 0)) return false;
+ return step >= 1 ? Math.abs(Math.round(step) - step) <= 1e-3 : Math.abs(1 / Math.round(1 / step) - step) <= 1e-3;
+}
+
+/** Face changes on a beat grid, seconds on the same clock as `beats`: every
+ * `step`th beat from the first one at or after `from`, or each beat split
+ * into 1/step parts, inside [from, to), closed by the run's end or one
+ * spacing past the last beat. Empty when no beat lands inside the run. */
+export function beatSwitches(beats: number[], step: number, from: number, to: number): number[] {
+ const whole = step >= 1 ? Math.round(step) : 1;
+ const parts = step < 1 ? Math.round(1 / step) : 1;
+ const first = beats.findIndex((t) => t >= from - 1e-6);
+ const picked = (first < 0 ? [] : beats.slice(first)).filter((_, i) => i % whole === 0);
+ const points = picked.flatMap((b, i) =>
+ i + 1 < picked.length ? Array.from({ length: parts }, (_, k) => b + ((picked[i + 1] - b) * k) / parts) : [b]
+ );
+ const inside = points.filter((t) => t >= from - 1e-6 && t < to - 1e-6);
+ if (inside.length === 0) return [];
+ const after = points.find((t) => t >= to - 1e-6);
+ const spacing = inside.length > 1 ? (inside[inside.length - 1] - inside[0]) / (inside.length - 1) : to - inside[0];
+ const close = after !== undefined ? to : Math.min(to, inside[inside.length - 1] + spacing);
+ return [...inside, close];
+}
+
+/** Switch times, seconds from the element's start, kept inside the element,
+ * in order, with a switch under a face's shortest hold after the one before
+ * it merged into it (the run's end is kept). */
+export function tidySwitches(edges: number[], dur: number): number[] {
+ const sorted = edges
+ .filter((t) => t >= -1e-6 && t <= dur + 1e-6)
+ .map((t) => Math.round(Math.max(0, Math.min(dur, t)) * 1e6) / 1e6)
+ .sort((a, b) => a - b);
+ const out: number[] = [];
+ for (const t of sorted) {
+ if (out.length > 0 && t - out[out.length - 1] < CYCLE_HOLD_MIN) {
+ if (t === sorted[sorted.length - 1] && out.length > 1) out[out.length - 1] = t;
+ continue;
+ }
+ out.push(t);
+ }
+ return out;
+}
+
+/** What keeps tidy switch times from timing a cycle: too few to hold one
+ * face, more faces than a cycle holds, or a gap longer than a face's longest
+ * hold (with that gap). Null when they time one. */
+export type SwitchProblem = { kind: "few" } | { kind: "many"; faces: number } | { kind: "long"; seconds: number };
+
+export function switchProblem(edges: number[]): SwitchProblem | null {
+ if (edges.length < 2) return { kind: "few" };
+ if (edges.length - 1 > FONT_CYCLE_FACES_MAX) return { kind: "many", faces: edges.length - 1 };
+ const longest = Math.max(...edges.slice(1).map((t, i) => t - edges[i]));
+ if (longest > CYCLE_HOLD_MAX) return { kind: "long", seconds: longest };
+ return null;
+}
+
+/** The cycle that shows one face per switch gap, the faces repeating in
+ * order to fill the gaps. `round` puts a time on the grid the caller keeps.
+ * Example: faces [a, b] over switches 0.5, 1, 2 → a at 0.5 for 0.5s, then b
+ * for 1s, and the title's own face after 2. */
+export function timedFontCycle(
+ faces: CycleFace[],
+ edges: number[],
+ rate: number,
+ round: (t: number) => number = (t) => t
+): OverlayFontCycle {
+ const timed = edges.slice(1).map((end, i) => ({ ...faces[i % faces.length], hold: round(end - edges[i]) }));
+ return { faces: timed, at: round(edges[0]), seconds: round(edges[edges.length - 1] - edges[0]), rate };
+}