Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
TL7c: captions made from what is said (CapCut's auto captions): sdk/timeline captions.ts heard() says a film's transcript where the edited cut plays it, captionLines() gathers the words into lines (a sentence's end, a 0.6 s pause, seven words or 42 characters), and the captions operation puts them as caption-style text clips on a Captions track of their own, one edit, undone whole; in a composition each line is a sequence of words (seqEdits). Five tests
shinyobjectzb41c609a0272
diff --git a/docs/timeline.feature b/docs/timeline.featureindex 47ad27a8..9a1ce8f1 100644--- a/docs/timeline.feature+++ b/docs/timeline.feature@@ -116,7 +116,14 @@ Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in theTL7a, TL7b for raea's ten effects (an effect is a clip of its own,shown on the player where it is on), TL7c (text added with T or in a style from the bar, drawn over afilm where it is on, renamed by a double-click, a caption split at the caret with Enter; raea's- four text styles and a plugin's, as data), a plugin's effects as data (timeline.effects in its manifest: parts+ four text styles and a plugin's, as data; and captions made from what is said, CapCut's auto+ captions: Captions in the bar transcribes the film first when it has no words yet, then puts the+ words, where the edited cut now says them (sdk/timeline captions.ts heard: a scene taken out takes+ its words, a duplicated one says them twice, a curved, reversed or frozen clip none), in lines (a+ sentence's end, a pause of 0.6 s, seven words or 42 characters end one) as text clips in the+ caption style on a Captions track of their own: one edit (the `captions` operation), undone+ whole, drawn over the film, told to the agent as one line with every caption's words and+ timecodes, and in a composition each line a sequence of words), a plugin's effects as data (timeline.effects in its manifest: partsof CSS filter functions, drawn by <Effect parts> and by the preview alike), TL8a(waveform, level line, fades; Cmd+. and Cmd+, step the level by 0.1 dB, or key it at theplayhead when it is keyed), TL8b's beats as ticks that edges snap to, each turned off by adiff --git a/sdk/timeline/src/captions.ts b/sdk/timeline/src/captions.tsnew file mode 100644index 00000000..25512b31--- /dev/null+++ b/sdk/timeline/src/captions.ts@@ -0,0 +1,63 @@+// Captions made from what is said (docs/timeline.feature TL7c, CapCut's auto captions): the transcript's words as+// the edited timeline says them, gathered into the lines a caption track shows one at a time. The `captions`+// operation (ops.ts) puts the lines on the timeline.+import { type Clip, end, type Frames, speedOf, type Timeline } from "./model"++/** A word, or a line of them: its text, its first frame and the frame after it ends. */+export interface Said {+ text: string+ start: Frames+ end: Frames+}++/** How words are gathered into lines. */+export interface LineRules {+ /** the most words on a line (7) */+ words?: number+ /** the most characters on a line, spaces counted (42) */+ chars?: number+ /** a pause at least this long starts a new line (0.6 s) */+ gap?: Frames+}++/** A clip that plays the film's own words as they were said: footage at a steady speed, forward. */+const speaks = (c: Clip) => !c.off && c.in !== undefined && !c.curve && !c.freeze && !c.reverse++/** The words as the edited timeline says them. `words` are in the film's own frames (where its transcript has them);+ * each is said where a main-track clip plays that part of the film, at that clip's speed. A word in a scene taken out+ * is gone, a scene duplicated says its words twice, and a clip curved, reversed or frozen says none. */+export function heard(t: Timeline, words: Said[]): Said[] {+ const main = (t.tracks.find((k) => k.kind === "main" && !k.hidden)?.clips ?? []).filter(speaks)+ const out: Said[] = []+ for (const w of words) {+ for (const c of main) {+ const v = speedOf(c), from = c.in!+ if (w.start < from || w.start >= from + c.length * v) continue+ const start = Math.round(c.start + (w.start - from) / v)+ const stop = Math.min(end(c), Math.round(c.start + (w.end - from) / v))+ out.push({ text: w.text, start, end: Math.max(start + 1, stop) })+ }+ }+ return out.sort((a, b) => a.start - b.start)+}++/** The words gathered into caption lines: a line ends after a sentence does, at a pause, or once it holds as many+ * words or characters as it may. Each line runs from its first word to its last and ends by the next line's start. */+export function captionLines(words: Said[], fps: number, o: LineRules = {}): Said[] {+ const most = o.words ?? 7, chars = o.chars ?? 42, gap = o.gap ?? Math.round(fps * 0.6)+ const lines: Said[] = []+ let line: Said[] = []+ const close = () => {+ if (line.length) lines.push({ text: line.map((w) => w.text).join(" "), start: line[0].start, end: line[line.length - 1].end })+ line = []+ }+ const said = words.map((w) => ({ ...w, text: w.text.trim() })).filter((w) => w.text).sort((a, b) => a.start - b.start)+ for (const w of said) {+ const last = line[line.length - 1]+ const long = [...line, w].map((x) => x.text).join(" ").length > chars+ if (last && (/[.!?…]["'”’)\]]?$/.test(last.text) || w.start - last.end >= gap || line.length >= most || long)) close()+ line.push(w)+ }+ close()+ return lines.map((l, i) => ({ ...l, end: Math.max(l.start + 1, Math.min(l.end, lines[i + 1]?.start ?? l.end)) }))+}diff --git a/sdk/timeline/src/index.ts b/sdk/timeline/src/index.tsindex 041796dd..cc42beba 100644--- a/sdk/timeline/src/index.ts+++ b/sdk/timeline/src/index.ts@@ -9,3 +9,4 @@ export * from "./read"export * from "./cache"export * from "./registry"export * from "./play"+export * from "./captions"diff --git a/sdk/timeline/src/ops.ts b/sdk/timeline/src/ops.tsindex 4bcf5765..81f751fe 100644--- a/sdk/timeline/src/ops.ts+++ b/sdk/timeline/src/ops.ts@@ -6,6 +6,7 @@ import { cut as cutKeys, sorted } from "./keys"import { type Clip, end, find, type Frames, type Key, type Marker, slot, speedOf, type SpeedPoint, type Timeline, type Track, type TrackKind, type Transition, type Value, type Ease } from "./model"import { fits } from "./snap"import { played } from "./speed"+import type { TextStyle } from "./registry"export type Op =/** clips moved in time by `by` frames, and (one kind's clips) onto track `track` */@@ -46,6 +47,9 @@ export type Op =/** a transition put on the cut after clip `after`, or changed (TL7a) */| { op: "transition"; transition: Transition }| { op: "untransition"; id: string }+ /** captions made from what is said (TL7c): each line a text clip in `style`, on a track of their own named Captions+ * (captions.ts makes the lines) */+ | { op: "captions"; lines: { text: string; start: Frames; end: Frames }[]; style: TextStyle }| { op: "option"; set: Partial<Pick<Timeline, "magnet" | "snapping" | "linkage">> }/** the timeline as it was: what every inverse is */| { op: "restore"; timeline: Timeline }@@ -318,6 +322,26 @@ function run(t: Timeline, op: Exclude<Op, { op: "restore" }>): Timeline {}case "untransition":return { ...t, transitions: t.transitions.filter((o) => o.id !== op.id) }+ case "captions": {+ // one line at a time, in order: a line starting before the one ahead of it ends starts where that one ends+ const taken = new Set(t.tracks.flatMap((k) => k.clips.map((c) => c.id)))+ let n = 1+ const clips: Clip[] = []+ for (const l of [...op.lines].sort((a, b) => a.start - b.start)) {+ const text = l.text.trim()+ const from = Math.max(0, whole(l.start), clips.length ? end(clips[clips.length - 1]) : 0)+ if (!text || whole(l.end) <= from) continue+ while (taken.has(`text-${n}`)) n+++ taken.add(`text-${n}`)+ clips.push({ id: `text-${n}`, kind: "text", name: text, start: from, length: whole(l.end) - from, props: { text: op.style.kind, style: JSON.stringify(op.style), said: true } })+ }+ if (!clips.length) no("there are no words to caption")+ let k = 1+ while (t.tracks.some((x) => x.id === (k === 1 ? "captions" : `captions-${k}`))) k+++ const tracks = [...t.tracks]+ tracks.splice(slot(tracks, "text"), 0, { id: k === 1 ? "captions" : `captions-${k}`, kind: "text", name: "Captions", clips })+ return { ...t, tracks }+ }case "option":return { ...t, ...op.set }}diff --git a/sdk/timeline/src/read.ts b/sdk/timeline/src/read.tsindex 4b404ea5..02b0576b 100644--- a/sdk/timeline/src/read.ts+++ b/sdk/timeline/src/read.ts@@ -367,6 +367,14 @@ export function seqEdits(t: Timeline, op: Op): SeqEdit[] | { why: string } {const style = textStyleOf(op.clip.props?.style)return [{ op: "text", at: Math.max(0, Math.round(op.clip.start)), frames: Math.max(1, Math.round(op.clip.length)), text: (op.clip.name ?? "Text").trim() || "Text", ...(style && { style }) }]}+ case "captions": {+ // captions made from what is said (TL7c): each line a sequence of words of its own, in the captions' style+ if (textStyleError(op.style)) return { why: `a caption's style ${textStyleError(op.style)}` }+ const tried = apply(t, op)+ if (!tried.ok) return { why: tried.why }+ const made = tried.timeline.tracks.find((k) => !t.tracks.some((o) => o.id === k.id))?.clips ?? []+ return made.map((c) => ({ op: "text", at: c.start, frames: c.length, text: c.name ?? "", style: op.style }))+ }default:return { why: `the composition's sequences don't take "${op.op}" yet` }}diff --git a/sdk/timeline/test/captions.test.ts b/sdk/timeline/test/captions.test.tsnew file mode 100644index 00000000..32ed2403--- /dev/null+++ b/sdk/timeline/test/captions.test.ts@@ -0,0 +1,85 @@+import { describe, expect, test } from "bun:test"+import { apply, captionLines, type Clip, empty, heard, type Said, TEXTS, type Timeline, seqEdits } from "../src"++const caption = TEXTS.find((s) => s.kind === "caption")!+const w = (text: string, start: number, end: number): Said => ({ text, start, end })+/** a film's scenes as a main track: a 0-30 (film 0-30), b 30-90 (film 30-90), c 90-120 (film 90-120) */+const film = (clips?: Clip[]): Timeline => ({+ ...empty(30),+ tracks: [+ {+ id: "main",+ kind: "main",+ clips: clips ?? [+ { id: "a", kind: "video", start: 0, length: 30, in: 0, source: 120 },+ { id: "b", kind: "video", start: 30, length: 60, in: 30, source: 120 },+ { id: "c", kind: "video", start: 90, length: 30, in: 90, source: 120 },+ ],+ },+ ],+})++describe("TL7c: captions made from what is said", () => {+ test("a line ends after a sentence, at a pause, or once it is full", () => {+ const said = [w("Hello", 0, 10), w("there.", 10, 20), w("This", 21, 25), w("is", 25, 28), w("raea", 28, 40), w("again", 70, 80)]+ expect(captionLines(said, 30)).toEqual([w("Hello there.", 0, 20), w("This is raea", 21, 40), w("again", 70, 80)])+ // seven words at most, and no more characters than a line holds+ const many = Array.from({ length: 10 }, (_, i) => w(`w${i}`, i * 5, i * 5 + 5))+ expect(captionLines(many, 30).map((l) => l.text)).toEqual(["w0 w1 w2 w3 w4 w5 w6", "w7 w8 w9"])+ expect(captionLines([w("supercalifragilistic", 0, 5), w("expialidocious", 5, 10)], 30, { chars: 20 }).map((l) => l.text)).toEqual(["supercalifragilistic", "expialidocious"])+ })++ test("a line ends by the next one's start, and blank words are left out", () => {+ expect(captionLines([w("One.", 0, 30), w(" ", 30, 31), w("Two", 20, 40)], 30)).toEqual([w("One.", 0, 20), w("Two", 20, 40)])+ })++ test("the words are said where the edited timeline plays them", () => {+ const said = [w("in-a", 5, 10), w("in-b", 40, 50), w("in-c", 95, 100)]+ // as cut: the same frames+ expect(heard(film(), said)).toEqual(said)+ // b taken out and the gap closed: c's word comes 60 frames earlier, b's is gone+ const cut = film([+ { id: "a", kind: "video", start: 0, length: 30, in: 0, source: 120 },+ { id: "c", kind: "video", start: 30, length: 30, in: 90, source: 120 },+ ])+ expect(heard(cut, said)).toEqual([w("in-a", 5, 10), w("in-c", 35, 40)])+ // a twice as fast: its word at half the frame; a duplicated says it twice; a reversed clip says none+ const fast = film([+ { id: "a", kind: "video", start: 0, length: 15, in: 0, source: 120, speed: 2 },+ { id: "a+", kind: "video", start: 15, length: 30, in: 0, source: 120 },+ { id: "b", kind: "video", start: 45, length: 60, in: 30, source: 120, reverse: true },+ ])+ expect(heard(fast, said)).toEqual([w("in-a", 3, 5), w("in-a", 20, 25)])+ })++ test("the captions are text clips in the captions' style on a track of their own, one undo away", () => {+ const t = film()+ const r = apply(t, { op: "captions", lines: [w("Hello there.", 0, 20), w("This is raea", 15, 40), w(" ", 50, 60)], style: caption })+ if (!r.ok) throw new Error(r.why)+ const track = r.timeline.tracks.find((k) => k.id === "captions")!+ expect(track).toMatchObject({ kind: "text", name: "Captions" })+ expect(r.timeline.tracks.indexOf(track)).toBeLessThan(r.timeline.tracks.findIndex((k) => k.id === "main"))+ expect(track.clips.map((c) => [c.id, c.name, c.start, c.length])).toEqual([+ ["text-1", "Hello there.", 0, 20],+ ["text-2", "This is raea", 20, 20],+ ])+ expect(JSON.parse(String(track.clips[0].props?.style))).toEqual(caption)+ expect(track.clips[0].props?.said).toBe(true)+ // undone, the track is gone+ const back = apply(r.timeline, r.inverse)+ expect(back.ok && back.timeline).toEqual(t)+ // made again, a second track beside it, with ids no clip has+ const again = apply(r.timeline, { op: "captions", lines: [w("More", 60, 70)], style: caption })+ expect(again.ok && again.timeline.tracks.find((k) => k.id === "captions-2")?.clips.map((c) => c.id)).toEqual(["text-3"])+ // nothing to say: refused+ expect(apply(t, { op: "captions", lines: [w(" ", 0, 10)], style: caption })).toEqual({ ok: false, why: "there are no words to caption" })+ })++ test("in a composition each line is a sequence of words of its own", () => {+ const t = film()+ expect(seqEdits(t, { op: "captions", lines: [w("Hello there.", 0, 20), w("This is raea", 21, 40)], style: caption })).toEqual([+ { op: "text", at: 0, frames: 20, text: "Hello there.", style: caption },+ { op: "text", at: 21, frames: 19, text: "This is raea", style: caption },+ ])+ })+})