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
TL0: in progress: sdk/timeline, the timeline's model and every edit as an operation
shinyobjectz53a5cc9ca76d
diff --git a/sdk/timeline/bun.lock b/sdk/timeline/bun.locknew file mode 100644index 00000000..ef586335--- /dev/null+++ b/sdk/timeline/bun.lock@@ -0,0 +1,23 @@+{+ "lockfileVersion": 2,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "@raea/timeline",+ "devDependencies": {+ "@types/bun": "1.4.3",+ },+ },+ },+ "packages": {+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],++ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],++ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],++ "undici-types": ["[email protected]", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="],++ "@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],+ }+}diff --git a/sdk/timeline/package.json b/sdk/timeline/package.jsonnew file mode 100644index 00000000..a8eff12f--- /dev/null+++ b/sdk/timeline/package.json@@ -0,0 +1,18 @@+{+ "name": "@raea/timeline",+ "license": "FSL-1.1-ALv2",+ "private": true,+ "version": "0.1.0",+ "description": "raea's timeline (docs/timeline.feature): tracks, clips, keys and markers, and every edit to them as a pure operation with its inverse. No React and no DOM: the app's strip, the host and an agent's script use the same model.",+ "type": "module",+ "main": "src/index.ts",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "test": "bun test test"+ },+ "devDependencies": {+ "@types/bun": "1.4.3"+ }+}diff --git a/sdk/timeline/src/index.ts b/sdk/timeline/src/index.tsnew file mode 100644index 00000000..3235aaf7--- /dev/null+++ b/sdk/timeline/src/index.ts@@ -0,0 +1,7 @@+// raea's timeline (docs/timeline.feature): the model, every edit as an operation, keys and their easing, speed+// curves, and snapping. No React and no DOM (TL11b).+export * from "./model"+export * from "./ops"+export * from "./keys"+export * from "./speed"+export * from "./snap"diff --git a/sdk/timeline/src/keys.ts b/sdk/timeline/src/keys.tsnew file mode 100644index 00000000..9e5cd2b7--- /dev/null+++ b/sdk/timeline/src/keys.ts@@ -0,0 +1,93 @@+// A keyed property's value at a frame (docs/timeline.feature TL5): between two keys it follows the first key's ease,+// before the first and after the last it holds. An ease is a cubic bezier's two handles, as CSS writes them.+import type { Ease, Frames, Key, Value } from "./model"++/** The easing presets raea registers (TL5c); a plugin adds its own beside them (TL11a). */+export const EASES: Record<string, Ease> = {+ linear: "linear",+ hold: "hold",+ "ease in": [0.42, 0, 1, 1],+ "ease out": [0, 0, 0.58, 1],+ "ease in-out": [0.42, 0, 0.58, 1],+}++/** y at x on the cubic bezier (0,0) (x1,y1) (x2,y2) (1,1): x is solved by Newton's steps, then bisection where the+ * slope is too flat for them. The handles' x are kept in 0..1 so the curve is a function of time. */+export function bezier(x1: number, y1: number, x2: number, y2: number): (x: number) => number {+ const a = Math.min(1, Math.max(0, x1)), b = Math.min(1, Math.max(0, x2))+ const at = (p1: number, p2: number, t: number) => 3 * p1 * t * (1 - t) * (1 - t) + 3 * p2 * t * t * (1 - t) + t * t * t+ const slope = (p1: number, p2: number, t: number) => 3 * p1 * (1 - t) * (1 - 3 * t) + 3 * p2 * t * (2 - 3 * t) + 3 * t * t+ return (x) => {+ if (x <= 0) return 0+ if (x >= 1) return 1+ let t = x+ for (let i = 0; i < 8; i++) {+ const d = slope(a, b, t)+ if (Math.abs(d) < 1e-6) break+ const next = t - (at(a, b, t) - x) / d+ if (Math.abs(next - t) < 1e-7) {+ t = next+ break+ }+ t = next+ }+ if (!(t >= 0 && t <= 1) || Math.abs(at(a, b, t) - x) > 1e-5) {+ let lo = 0, hi = 1+ for (let i = 0; i < 40; i++) {+ t = (lo + hi) / 2+ if (at(a, b, t) < x) lo = t+ else hi = t+ }+ }+ return at(y1, y2, t)+ }+}++/** How far along (0..1, or past it for a handle that overshoots) a value is at `p` of the way between two keys. */+export function eased(ease: Ease | undefined, p: number): number {+ if (ease === "hold") return p >= 1 ? 1 : 0+ if (!ease || ease === "linear") return Math.min(1, Math.max(0, p))+ return bezier(...ease)(p)+}++const mix = (a: Value, b: Value, k: number): Value => {+ if (typeof a === "number" && typeof b === "number") return a + (b - a) * k+ if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) return a.map((v, i) => v + (b[i] - v) * k)+ // what can't be mixed (words, lists of different lengths) holds, then jumps+ return k >= 1 ? b : a+}++/** The keys in time order (two at one frame: the later one written wins). */+export const sorted = (keys: Key[]): Key[] => {+ const by = new Map<Frames, Key>()+ for (const k of keys) by.set(k.at, k)+ return [...by.values()].sort((a, b) => a.at - b.at)+}++/** The property's value at `frame` (frames from its clip's start), or undefined with no keys. */+export function valueAt(keys: Key[] | undefined, frame: Frames): Value | undefined {+ if (!keys?.length) return undefined+ const ks = sorted(keys)+ if (frame <= ks[0].at) return ks[0].value+ const last = ks[ks.length - 1]+ if (frame >= last.at) return last.value+ const i = ks.findIndex((k) => k.at > frame) - 1+ const a = ks[i], b = ks[i + 1]+ return mix(a.value, b.value, eased(a.ease, (frame - a.at) / (b.at - a.at)))+}++/** The keys either side of a cut at `frame` (TL3d: a split clip's keys stay at their frames): the left clip's, and+ * the right clip's in its own frames. A cut between two keys puts a key of the value there on both sides, so each+ * half moves as the whole did up to the cut. */+export function cut(keys: Key[], frame: Frames): [Key[], Key[]] {+ const ks = sorted(keys)+ const left = ks.filter((k) => k.at < frame)+ const right = ks.filter((k) => k.at >= frame).map((k) => ({ ...k, at: k.at - frame }))+ const between = left.length > 0 && ks.some((k) => k.at > frame) && !ks.some((k) => k.at === frame)+ if (between) {+ const value = valueAt(ks, frame)!+ left.push({ at: frame, value })+ right.unshift({ at: 0, value, ease: left[left.length - 2].ease })+ }+ return [left, right]+}diff --git a/sdk/timeline/src/model.ts b/sdk/timeline/src/model.tsnew file mode 100644index 00000000..6c3f694a--- /dev/null+++ b/sdk/timeline/src/model.ts@@ -0,0 +1,132 @@+// The timeline's model (docs/timeline.feature TL0). Time is whole frames (TL0a): a clip's start, length and trim, a+// key and a marker are integers; seconds and timecodes are drawn from them, never the other way.++export type Frames = number++/** A track's kind, in the order they stack from the top (TL1a): effect, text, overlay, main, sound. A plugin adds+ * its own (TL11a); an unknown kind sorts with the overlays. */+export type TrackKind = "effect" | "text" | "overlay" | "main" | "sound" | (string & {})+export const ORDER: TrackKind[] = ["effect", "text", "overlay", "main", "sound"]++/** How a value travels from one key to the next: a straight line, no travel (it holds, then jumps), or a cubic+ * bezier's two handles [x1, y1, x2, y2] as CSS writes them (TL5c). */+export type Ease = "linear" | "hold" | [number, number, number, number]++export type Value = number | number[] | string++/** A property's value at a frame of its clip (frames from the clip's start), and how it leaves for the next key. */+export interface Key {+ at: Frames+ value: Value+ ease?: Ease+}++/** A point of a speed curve (TL6b): how fast the source plays at a place in it (0 its first frame shown, 1 its last). */+export interface SpeedPoint {+ at: number+ speed: number+}++export interface Marker {+ id: string+ at: Frames+ name?: string+ color?: string+}++export interface Clip {+ id: string+ /** what it is: "video", "audio", "text", "sequence", "component", "effect", a plugin's own */+ kind: string+ name?: string+ /** where it starts on the timeline, and for how long */+ start: Frames+ length: Frames+ /** media: the first source frame it shows, and how many frames the source has (unset: no end to trim against) */+ in?: Frames+ source?: Frames+ /** a constant speed (1 when unset), or a curve, which wins (TL6) */+ speed?: number+ curve?: SpeedPoint[]+ /** turned off: drawn dimmed, left out of the picture and the sound (TL3g) */+ off?: boolean+ /** it can't be changed here, and why ("set in code", TL0c) */+ locked?: string+ /** clips with one group pick and move as one (TL3g) */+ group?: string+ /** still values, and keyed ones (TL5): a keyed property's still value is ignored */+ props?: Record<string, Value | boolean>+ keys?: Record<string, Key[]>+ /** sound: its level (1 as recorded) and its fades' lengths (TL8a) */+ volume?: number+ fadeIn?: Frames+ fadeOut?: Frames+ /** its element in the code (file:line:col, docs/editing.feature E2) */+ at?: string+ /** markers on the clip itself, in frames from its start (TL2e) */+ markers?: Marker[]+}++export interface Track {+ id: string+ kind: TrackKind+ name?: string+ locked?: boolean+ hidden?: boolean+ muted?: boolean+ /** drawn this tall, in px (TL1c) */+ height?: number+ clips: Clip[]+}++/** A transition on the cut between two clips that touch on one track (TL7a): the cut is the end of clip `after`,+ * so it follows that cut wherever an edit moves it. */+export interface Transition {+ id: string+ kind: string+ after: string+ length: Frames+}++export interface Timeline {+ fps: number+ tracks: Track[]+ markers: Marker[]+ transitions: Transition[]+ /** the main track holds no gap (TL4a), edges snap (TL4b), what sits over a main clip follows it (TL4c) */+ magnet: boolean+ snapping: boolean+ linkage: boolean+}++export const empty = (fps = 30): Timeline => ({ fps, tracks: [], markers: [], transitions: [], magnet: true, snapping: true, linkage: true })++export const end = (c: Clip): Frames => c.start + c.length+/** The timeline's length: its last clip's end. */+export const length = (t: Timeline): Frames => Math.max(0, ...t.tracks.flatMap((k) => k.clips.map(end)))+export const clips = (t: Timeline): Clip[] => t.tracks.flatMap((k) => k.clips)+export const find = (t: Timeline, id: string): { track: Track; clip: Clip } | undefined => {+ for (const track of t.tracks) {+ const clip = track.clips.find((c) => c.id === id)+ if (clip) return { track, clip }+ }+}+/** A clip's speed where it is constant. */+export const speedOf = (c: Clip): number => (c.speed && c.speed > 0 ? c.speed : 1)++/** mm:ss:ff, drawn from frames (TL0a). */+export function timecode(frames: Frames, fps: number): string {+ const f = Math.max(0, Math.round(frames))+ const whole = Math.round(fps)+ const two = (n: number) => String(n).padStart(2, "0")+ return `${two(Math.floor(f / whole / 60))}:${two(Math.floor(f / whole) % 60)}:${two(f % whole)}`+}++/** Where a track of this kind goes among the others (TL1a): after the last of its own kind, else in ORDER's place. */+export function slot(tracks: Track[], kind: TrackKind): number {+ const rank = (k: TrackKind) => (ORDER.includes(k) ? ORDER.indexOf(k) : ORDER.indexOf("overlay"))+ // sound tracks grow downward (a new one goes under the others); every other kind grows upward+ if (kind === "sound") return tracks.length+ const first = tracks.findIndex((t) => rank(t.kind) >= rank(kind))+ return first < 0 ? tracks.length : first+}diff --git a/sdk/timeline/src/ops.ts b/sdk/timeline/src/ops.tsnew file mode 100644index 00000000..66b4b8ae--- /dev/null+++ b/sdk/timeline/src/ops.ts@@ -0,0 +1,332 @@+// Every edit to a timeline as an operation (docs/timeline.feature TL0b): a pure function from a timeline to the+// next, refused with its reason when it can't apply, and answered with its inverse so undo is another operation.+// After each one the timeline is settled: the main track closed while its magnet is on (TL4a), what sits over a+// main clip carried with it while linkage is on (TL4c), transitions kept only on cuts that still exist.+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"++export type Op =+ /** clips moved in time by `by` frames, and (one kind's clips) onto track `track` */+ | { op: "move"; ids: string[]; by: Frames; track?: string }+ /** a clip's start or end dragged to the timeline frame `to` */+ | { op: "trim"; id: string; edge: "start" | "end"; to: Frames }+ /** the clips `ids` split at `at`; with none named, every clip under it (Cmd+B, Cmd+Shift+B: TL3d) */+ | { op: "split"; at: Frames; ids?: string[] }+ /** clips removed; `ripple` closes the gap on any track (Shift+Delete, TL3e) */+ | { op: "remove"; ids: string[]; ripple?: boolean }+ /** what is left (Q) or right (W) of `at` on a clip removed, the gap closed (TL3e) */+ | { op: "cut"; id: string; side: "left" | "right"; at: Frames }+ | { op: "duplicate"; ids: string[] }+ /** a clip put on the timeline: on `track`, else the first of `kind` with room, else a new track of that kind */+ | { op: "add"; kind: TrackKind; clip: Clip; track?: string }+ /** a clip's own fields; `props` are merged into its props; a speed or a curve changes its length (TL6) */+ | { op: "set"; id: string; set: Partial<Pick<Clip, "name" | "off" | "volume" | "fadeIn" | "fadeOut" | "speed" | "group">> & { curve?: SpeedPoint[] | null; props?: Record<string, Value | boolean> } }+ /** a property's key at a frame of its clip: made, or its value (and ease) changed (TL5a) */+ | { op: "key"; id: string; prop: string; at: Frames; value: Value; ease?: Ease }+ | { op: "unkey"; id: string; prop: string; at: Frames }+ | { op: "moveKey"; id: string; prop: string; at: Frames; to: Frames }+ | { op: "ease"; id: string; prop: string; at: Frames; ease: Ease }+ /** a marker made or changed (by its id), on the timeline or on clip `clip` (TL2e) */+ | { op: "mark"; marker: Marker; clip?: string }+ | { op: "unmark"; id: string; clip?: string }+ | { op: "track"; id: string; set: Partial<Pick<Track, "name" | "locked" | "hidden" | "muted" | "height">> }+ /** a transition put on the cut after clip `after`, or changed (TL7a) */+ | { op: "transition"; transition: Transition }+ | { op: "untransition"; id: string }+ | { op: "option"; set: Partial<Pick<Timeline, "magnet" | "snapping" | "linkage">> }+ /** the timeline as it was: what every inverse is */+ | { op: "restore"; timeline: Timeline }++export type Applied = { ok: true; timeline: Timeline; inverse: Op } | { ok: false; why: string }++class Refused extends Error {}+const no = (why: string): never => {+ throw new Refused(why)+}+const whole = (n: number) => Math.round(n)++/** The operation applied, or why it can't be. */+export function apply(t: Timeline, op: Op): Applied {+ try {+ const next = op.op === "restore" ? op.timeline : settle(t, run(t, op), op)+ return { ok: true, timeline: next, inverse: { op: "restore", timeline: t } }+ } catch (e) {+ if (e instanceof Refused) return { ok: false, why: e.message }+ throw e+ }+}++/** Operations in order, stopping at the first refused: the timeline they give, and each one's inverse (last first). */+export function applyAll(t: Timeline, ops: Op[]): { timeline: Timeline; inverse: Op[]; refused?: { op: Op; why: string } } {+ const inverse: Op[] = []+ for (const op of ops) {+ const r = apply(t, op)+ if (!r.ok) return { timeline: t, inverse, refused: { op, why: r.why } }+ inverse.unshift(r.inverse)+ t = r.timeline+ }+ return { timeline: t, inverse }+}++// ---------------------------------------------------------------- reading and rewriting++/** The clip and its track, when both can be changed. */+function open(t: Timeline, id: string): { track: Track; clip: Clip } {+ const at = find(t, id) ?? no(`there is no clip ${id}`)+ if (at.track.locked) no(`${at.track.name ?? "that track"} is locked`)+ if (at.clip.locked) no(`${at.clip.name ?? at.clip.id} is ${at.clip.locked}`)+ return at+}+const withTracks = (t: Timeline, f: (k: Track) => Track): Timeline => ({ ...t, tracks: t.tracks.map(f) })+const change = (t: Timeline, id: string, f: (c: Clip) => Clip): Timeline => withTracks(t, (k) => (k.clips.some((c) => c.id === id) ? { ...k, clips: k.clips.map((c) => (c.id === id ? f(c) : c)) } : k))+/** An id no clip has, made from `id`. */+function fresh(t: Timeline, id: string, taken: Set<string> = new Set()): string {+ let n = `${id}+`+ while (find(t, n) || taken.has(n)) n += "+"+ taken.add(n)+ return n+}+/** How many source frames a clip shows. */+const shown = (c: Clip): number => (c.curve ? c.length / played(c.curve, 1) : c.length * speedOf(c))+const isMain = (k: Track) => k.kind === "main"++/** `clip` on the timeline: on `prefer` if it has room there, else the first track of `kind` with room, else a new+ * track of that kind in its place (TL1a, TL4a: a clip dropped over another goes to a track of its own). */+function place(t: Timeline, kind: TrackKind, clip: Clip, prefer?: string): Timeline {+ const ok = (k: Track) => !k.locked && (isMain(k) ? t.magnet || fits(k, clip) : fits(k, clip))+ const want = prefer ? t.tracks.find((k) => k.id === prefer) : undefined+ if (want?.locked) no(`${want.name ?? "that track"} is locked`)+ const home = (want && ok(want) ? want : undefined) ?? (kind === "main" ? undefined : t.tracks.find((k) => k.kind === kind && ok(k))) ?? (kind === "main" ? t.tracks.find((k) => isMain(k) && ok(k)) : undefined)+ if (home) return withTracks(t, (k) => (k.id === home.id ? { ...k, clips: [...k.clips, clip] } : k))+ // no room on the main track (its magnet off): the clip becomes an overlay+ const made: TrackKind = kind === "main" && t.tracks.some(isMain) ? "overlay" : kind+ let n = 1+ while (t.tracks.some((k) => k.id === `${made}-${n}`)) n+++ const tracks = [...t.tracks]+ tracks.splice(slot(tracks, made), 0, { id: `${made}-${n}`, kind: made, clips: [clip] })+ return { ...t, tracks }+}++// ---------------------------------------------------------------- the operations++function run(t: Timeline, op: Exclude<Op, { op: "restore" }>): Timeline {+ switch (op.op) {+ case "move": {+ const by = whole(op.by)+ const moving = op.ids.map((id) => open(t, id))+ if (!moving.length) no("nothing is picked")+ if (Math.min(...moving.map((m) => m.clip.start)) + by < 0) no("it would start before the film does")+ const ids = new Set(op.ids)+ // lifted off their tracks, then each put down where it lands: its own track, the one named, or one with room+ let next = withTracks(t, (k) => ({ ...k, clips: k.clips.filter((c) => !ids.has(c.id)) }))+ for (const m of moving) {+ const to = op.track ? (t.tracks.find((k) => k.id === op.track) ?? no(`there is no track ${op.track}`)) : m.track+ if (to.kind !== m.track.kind && !(isMain(to) || isMain(m.track)) ) no(`a ${m.track.kind} clip doesn't go on a ${to.kind} track`)+ next = place(next, to.kind, { ...m.clip, start: m.clip.start + by }, to.id)+ }+ return next+ }+ case "trim": {+ const { track, clip } = open(t, op.id)+ const to = whole(op.to), speed = speedOf(clip)+ if (op.edge === "start") {+ // back out no further than the source's first frame, in no further than one frame of clip+ const least = clip.in === undefined ? 0 : clip.start - Math.floor(clip.in / speed)+ const before = isMain(track) && t.magnet ? 0 : Math.max(0, ...track.clips.filter((c) => c.id !== clip.id && end(c) <= clip.start).map(end))+ const start = Math.min(end(clip) - 1, Math.max(to, least, before, 0))+ const d = start - clip.start+ if (!d) return t+ return change(t, clip.id, (c) => ({ ...c, start, length: c.length - d, ...(c.in !== undefined && { in: Math.max(0, c.in + Math.round(d * speed)) }), ...(c.keys && { keys: shiftKeys(c.keys, d) }), ...(c.markers && { markers: c.markers.map((m) => ({ ...m, at: m.at - d })).filter((m) => m.at >= 0) }) }))+ }+ const most = clip.source === undefined || clip.curve ? Infinity : clip.start + Math.floor((clip.source - (clip.in ?? 0)) / speed)+ const after = isMain(track) && t.magnet ? Infinity : Math.min(Infinity, ...track.clips.filter((c) => c.id !== clip.id && c.start >= end(clip)).map((c) => c.start))+ const stop = Math.max(clip.start + 1, Math.min(to, most, after))+ return stop === end(clip) ? t : change(t, clip.id, (c) => ({ ...c, length: stop - c.start }))+ }+ case "split": {+ const at = whole(op.at)+ const under = (c: Clip) => c.start < at && at < end(c)+ const named = op.ids ? op.ids.map((id) => open(t, id).clip) : t.tracks.filter((k) => !k.locked).flatMap((k) => k.clips.filter((c) => under(c) && !c.locked))+ const cutting = named.filter(under)+ if (!cutting.length) no("no clip is under the playhead")+ const ids = new Set(cutting.map((c) => c.id)), taken = new Set<string>()+ return withTracks(t, (k) => ({ ...k, clips: k.clips.flatMap((c) => (ids.has(c.id) ? halves(c, at, fresh(t, c.id, taken)) : [c])) }))+ }+ case "remove": {+ const gone = op.ids.map((id) => open(t, id))+ if (!gone.length) no("nothing is picked")+ const ids = new Set(op.ids)+ return withTracks(t, (k) => {+ if (!k.clips.some((c) => ids.has(c.id))) return k+ const out = k.clips.filter((c) => ids.has(c.id))+ // each later clip moves back by what was removed before it+ const back = (c: Clip) => (op.ripple && !isMain(k) ? out.filter((o) => o.start < c.start).reduce((n, o) => n + o.length, 0) : 0)+ return { ...k, clips: k.clips.filter((c) => !ids.has(c.id)).map((c) => (back(c) ? { ...c, start: c.start - back(c) } : c)) }+ })+ }+ case "cut": {+ const { track, clip } = open(t, op.id)+ const at = whole(op.at)+ if (!(clip.start < at && at < end(clip))) no("the playhead isn't on that clip")+ const [left, right] = halves(clip, at, clip.id)+ const kept = op.side === "left" ? { ...right, start: clip.start } : left+ const lost = clip.length - kept.length+ return withTracks(t, (k) => (k.id !== track.id ? k : { ...k, clips: k.clips.map((c) => (c.id === clip.id ? kept : !isMain(k) && c.start >= end(clip) ? { ...c, start: c.start - lost } : c)) }))+ }+ case "duplicate": {+ const taken = new Set<string>()+ let next = t+ for (const id of op.ids) {+ const { track, clip } = open(t, id)+ const copy = { ...clip, id: fresh(t, id, taken), start: end(clip), group: undefined }+ // on a track with no magnet, what comes after makes room for it+ if (!(isMain(track) && t.magnet)) next = withTracks(next, (k) => (k.id === track.id ? { ...k, clips: k.clips.map((c) => (c.start >= end(clip) ? { ...c, start: c.start + clip.length } : c)) } : k))+ next = place(next, track.kind, copy, track.id)+ }+ return next+ }+ case "add": {+ if (find(t, op.clip.id)) no(`there is already a clip ${op.clip.id}`)+ if (!(op.clip.length >= 1) || op.clip.start < 0) no("a clip is at least one frame long and starts in the film")+ return place(t, op.kind, { ...op.clip, start: whole(op.clip.start), length: whole(op.clip.length) }, op.track)+ }+ case "set": {+ const { clip } = open(t, op.id)+ const { props, curve, ...rest } = op.set+ let c: Clip = { ...clip, ...rest, ...(props && { props: { ...clip.props, ...props } }) }+ const source = shown(clip)+ if (curve !== undefined || (rest.speed !== undefined && rest.speed !== clip.speed)) {+ if (rest.speed !== undefined && !(rest.speed > 0)) no("a speed is more than 0")+ const points = curve === undefined ? clip.curve : (curve ?? undefined)+ // the same frames of source, at the new pace+ c = { ...c, curve: points, length: Math.max(1, whole(points ? played(points, source) : source / speedOf(c))) }+ }+ return change(t, clip.id, () => c)+ }+ case "key":+ case "unkey":+ case "moveKey":+ case "ease": {+ const { clip } = open(t, op.id)+ const at = whole(op.at)+ const had = clip.keys?.[op.prop] ?? []+ const here = had.find((k) => k.at === at)+ let keys: Key[]+ if (op.op === "key") {+ if (at < 0 || at > clip.length) no("a key is inside its clip")+ keys = [...had.filter((k) => k.at !== at), { at, value: op.value, ...((op.ease ?? here?.ease) !== undefined && { ease: op.ease ?? here?.ease }) }]+ } else {+ if (!here) no(`${op.prop} has no key there`)+ if (op.op === "unkey") keys = had.filter((k) => k.at !== at)+ else if (op.op === "ease") keys = had.map((k) => (k.at === at ? { ...k, ease: op.ease } : k))+ else {+ const to = whole(op.to)+ if (to < 0 || to > clip.length) no("a key is inside its clip")+ keys = [...had.filter((k) => k.at !== at && k.at !== to), { ...here!, at: to }]+ }+ }+ const all = { ...clip.keys, [op.prop]: sorted(keys) }+ if (!keys.length) delete all[op.prop]+ return change(t, clip.id, (c) => ({ ...c, keys: Object.keys(all).length ? all : undefined }))+ }+ case "mark":+ case "unmark": {+ const id = op.op === "mark" ? op.marker.id : op.id+ const put = (ms: Marker[] = []) => [...ms.filter((m) => m.id !== id), ...(op.op === "mark" ? [{ ...op.marker, at: whole(op.marker.at) }] : [])].sort((a, b) => a.at - b.at)+ if (op.clip) return change(t, open(t, op.clip).clip.id, (c) => ({ ...c, markers: put(c.markers) }))+ return { ...t, markers: put(t.markers) }+ }+ case "track": {+ if (!t.tracks.some((k) => k.id === op.id)) no(`there is no track ${op.id}`)+ return withTracks(t, (k) => (k.id === op.id ? { ...k, ...op.set } : k))+ }+ case "transition": {+ const x = op.transition+ const { track, clip } = open(t, x.after)+ const next = track.clips.find((c) => c.start === end(clip)) ?? no("a transition sits on a cut: no clip starts where that one ends")+ // no longer than either clip can give it+ const length = Math.max(1, Math.min(whole(x.length), clip.length, next.length))+ return { ...t, transitions: [...t.transitions.filter((o) => o.id !== x.id && o.after !== x.after), { ...x, length }] }+ }+ case "untransition":+ return { ...t, transitions: t.transitions.filter((o) => o.id !== op.id) }+ case "option":+ return { ...t, ...op.set }+ }+}++/** A clip's keys after its start moved in by `d` frames (out, when negative): they stay at their timeline frames. */+function shiftKeys(keys: Record<string, Key[]>, d: Frames): Record<string, Key[]> {+ return Object.fromEntries(Object.entries(keys).map(([p, ks]) => [p, d > 0 ? cutKeys(ks, d)[1] : ks.map((k) => ({ ...k, at: k.at - d }))]))+}++/** A clip as its two parts either side of timeline frame `at`: the left keeps its id, the right takes `id`. Media+ * keep their place in the source, keys stay at their frames, each fade stays on its own end. */+function halves(c: Clip, at: Frames, id: string): [Clip, Clip] {+ const d = at - c.start+ const parts = Object.entries(c.keys ?? {}).map(([p, ks]) => [p, cutKeys(ks, d)] as const)+ const keysOf = (i: 0 | 1) => {+ const ks = Object.fromEntries(parts.filter(([, h]) => h[i].length).map(([p, h]) => [p, h[i]]))+ return Object.keys(ks).length ? ks : undefined+ }+ const left: Clip = { ...c, length: d, fadeOut: undefined, keys: keysOf(0), markers: c.markers?.filter((m) => m.at < d) }+ const right: Clip = { ...c, id, start: at, length: c.length - d, fadeIn: undefined, keys: keysOf(1), markers: c.markers?.filter((m) => m.at >= d).map((m) => ({ ...m, at: m.at - d })), ...(c.in !== undefined && { in: c.in + Math.round(d * speedOf(c)) }) }+ return [left, right]+}++// ---------------------------------------------------------------- settling++/** `next` made whole after `op` changed `was`: the main track closed (the magnet), followers carried (linkage),+ * tracks in time order, empty made tracks gone, transitions only on cuts that are still there. */+function settle(was: Timeline, next: Timeline, op: Op): Timeline {+ const named = new Set("ids" in op && op.ids ? op.ids : "id" in op && typeof op.id === "string" ? [op.id] : [])+ let t = next+ if (t.magnet) t = withTracks(t, (k) => (isMain(k) ? { ...k, clips: close(k.clips) } : k))+ if (was.linkage && t.linkage && op.op !== "option") t = follow(was, t, op, named)+ t = { ...t, tracks: t.tracks.filter((k) => k.clips.length || was.tracks.some((o) => o.id === k.id)).map((k) => ({ ...k, clips: [...k.clips].sort((a, b) => a.start - b.start) })) }+ const cut = (x: Transition) => {+ const at = find(t, x.after)+ return !!at && at.track.clips.some((c) => c.start === end(at.clip))+ }+ return t.transitions.every(cut) ? t : { ...t, transitions: t.transitions.filter(cut) }+}++/** The main track's clips with no gap, from frame 0. A clip the operation moved takes its place by its middle, so+ * it swaps with a neighbour once it is dragged past that neighbour's middle (TL4a). */+function close(clips: Clip[]): Clip[] {+ // (clips that don't overlap are in the same order by their middles as by their starts)+ const key = (c: Clip) => c.start + c.length / 2+ let at = 0+ return [...clips]+ .sort((a, b) => key(a) - key(b))+ .map((c) => {+ const moved = c.start === at ? c : { ...c, start: at }+ at += c.length+ return moved+ })+}++/** What sat over a main clip goes where that clip went, and goes when it is removed (TL4c): picture, text and effect+ * clips whose start was inside its span, unless the operation named them itself. */+function follow(was: Timeline, t: Timeline, op: Op, named: Set<string>): Timeline {+ const mains = was.tracks.filter(isMain).flatMap((k) => k.clips)+ if (!mains.length) return t+ const over = (c: Clip) => mains.find((m) => m.start <= c.start && c.start < end(m))+ const fate = new Map<string, number | "gone">()+ for (const k of was.tracks) {+ if (isMain(k) || k.kind === "sound" || k.locked) continue+ for (const c of k.clips) {+ if (named.has(c.id)) continue+ const m = over(c)+ if (!m) continue+ const now = find(t, m.id)+ if (!now) {+ if (op.op === "remove") fate.set(c.id, "gone")+ } else if (now.clip.start !== m.start && op.op !== "trim" && op.op !== "cut") fate.set(c.id, now.clip.start - m.start)+ }+ }+ if (!fate.size) return t+ return withTracks(t, (k) => ({ ...k, clips: k.clips.filter((c) => fate.get(c.id) !== "gone").map((c) => (typeof fate.get(c.id) === "number" ? { ...c, start: Math.max(0, c.start + (fate.get(c.id) as number)) } : c)) }))+}diff --git a/sdk/timeline/src/snap.ts b/sdk/timeline/src/snap.tsnew file mode 100644index 00000000..f70b3c09--- /dev/null+++ b/sdk/timeline/src/snap.ts@@ -0,0 +1,43 @@+// What an edge snaps to (docs/timeline.feature TL4b): clip edges on every track, the playhead, markers, a sound's+// beats and the film's ends. (The main track's magnet is the operations' own: ops.ts settles it.)+import { type Clip, end, type Frames, type Timeline, type Track } from "./model"++export interface Target {+ at: Frames+ /** what is there, for the line drawn where it snapped */+ what: "clip" | "playhead" | "marker" | "beat" | "start"+}++/** Every frame an edge can snap to, leaving out the clips being moved (`not`). */+export function targets(t: Timeline, o: { not?: string[]; playhead?: Frames; beats?: Frames[] } = {}): Target[] {+ const skip = new Set(o.not ?? [])+ const out: Target[] = [{ at: 0, what: "start" }]+ for (const k of t.tracks)+ for (const c of k.clips) {+ if (skip.has(c.id)) continue+ out.push({ at: c.start, what: "clip" }, { at: end(c), what: "clip" })+ for (const m of c.markers ?? []) out.push({ at: c.start + m.at, what: "marker" })+ }+ for (const m of t.markers) out.push({ at: m.at, what: "marker" })+ for (const b of o.beats ?? []) out.push({ at: b, what: "beat" })+ if (o.playhead !== undefined) out.push({ at: o.playhead, what: "playhead" })+ return out+}++/** `frame` moved to the nearest target within `within` frames (8 px at the strip's zoom), and what it snapped to. */+export function snap(frame: Frames, to: Target[], within: Frames): { frame: Frames; to?: Target } {+ let best: Target | undefined+ for (const x of to) if (Math.abs(x.at - frame) <= within && (!best || Math.abs(x.at - frame) < Math.abs(best.at - frame))) best = x+ return best ? { frame: best.at, to: best } : { frame: Math.round(frame) }+}++/** A moved clip (its start and length) snapped by whichever of its edges is nearer a target: how far it moves. */+export function snapMove(start: Frames, len: Frames, to: Target[], within: Frames): { by: Frames; to?: Target } {+ const a = snap(start, to, within), b = snap(start + len, to, within)+ if (a.to && (!b.to || Math.abs(a.frame - start) <= Math.abs(b.frame - (start + len)))) return { by: a.frame - start, to: a.to }+ if (b.to) return { by: b.frame - (start + len), to: b.to }+ return { by: 0 }+}++/** Whether `c` has room on the track (it overlaps none of the others). */+export const fits = (track: Track, c: Pick<Clip, "id" | "start" | "length">): boolean => track.clips.every((o) => o.id === c.id || o.start >= c.start + c.length || end(o) <= c.start)diff --git a/sdk/timeline/src/speed.ts b/sdk/timeline/src/speed.tsnew file mode 100644index 00000000..6d080163--- /dev/null+++ b/sdk/timeline/src/speed.ts@@ -0,0 +1,68 @@+// A clip's speed (docs/timeline.feature TL6): constant, or a curve of points over its source, each from 0.1x to 10x.+// Between two points the speed changes in a straight line over the source, so the time a span of source takes and+// the source frame at a time both have closed forms.+import type { SpeedPoint } from "./model"++export const SLOWEST = 0.1+export const FASTEST = 10+const clamp = (v: number) => Math.min(FASTEST, Math.max(SLOWEST, v))++/** CapCut's curve presets (TL6b), as points over the source; a plugin adds its own (TL11a). */+export const CURVES: Record<string, SpeedPoint[]> = {+ montage: [{ at: 0, speed: 1 }, { at: 0.25, speed: 3 }, { at: 0.5, speed: 0.5 }, { at: 0.75, speed: 3 }, { at: 1, speed: 1 }],+ hero: [{ at: 0, speed: 1 }, { at: 0.3, speed: 5 }, { at: 0.5, speed: 0.4 }, { at: 0.7, speed: 5 }, { at: 1, speed: 1 }],+ bullet: [{ at: 0, speed: 5 }, { at: 0.4, speed: 5 }, { at: 0.5, speed: 0.3 }, { at: 0.6, speed: 5 }, { at: 1, speed: 5 }],+ "jump cut": [{ at: 0, speed: 0.5 }, { at: 0.45, speed: 0.5 }, { at: 0.5, speed: 6 }, { at: 0.55, speed: 0.5 }, { at: 1, speed: 0.5 }],+ "flash in": [{ at: 0, speed: 5 }, { at: 0.4, speed: 2 }, { at: 1, speed: 1 }],+ "flash out": [{ at: 0, speed: 1 }, { at: 0.6, speed: 2 }, { at: 1, speed: 5 }],+}++/** The curve as points from 0 to 1 in order, each speed in range. */+export function points(curve: SpeedPoint[]): SpeedPoint[] {+ const ps = curve.map((p) => ({ at: Math.min(1, Math.max(0, p.at)), speed: clamp(p.speed) })).sort((a, b) => a.at - b.at)+ if (!ps.length) return [{ at: 0, speed: 1 }, { at: 1, speed: 1 }]+ if (ps[0].at > 0) ps.unshift({ at: 0, speed: ps[0].speed })+ if (ps[ps.length - 1].at < 1) ps.push({ at: 1, speed: ps[ps.length - 1].speed })+ return ps+}++// the time `span` of source takes while the speed goes from v0 to v1 across it+const took = (span: number, v0: number, v1: number) => (Math.abs(v1 - v0) < 1e-9 ? span / v0 : (span * Math.log(v1 / v0)) / (v1 - v0))++/** How many frames `source` frames of source take to play under the curve. */+export function played(curve: SpeedPoint[], source: number): number {+ const ps = points(curve)+ let t = 0+ for (let i = 0; i + 1 < ps.length; i++) t += took((ps[i + 1].at - ps[i].at) * source, ps[i].speed, ps[i + 1].speed)+ return t+}++/** The source frame showing `time` frames into the clip, under the curve over `source` frames of source. */+export function sourceAt(curve: SpeedPoint[], source: number, time: number): number {+ const ps = points(curve)+ let t = Math.max(0, time)+ for (let i = 0; i + 1 < ps.length; i++) {+ const span = (ps[i + 1].at - ps[i].at) * source, v0 = ps[i].speed, v1 = ps[i + 1].speed+ const whole = took(span, v0, v1)+ if (t > whole) {+ t -= whole+ continue+ }+ // within this span: v(s) = v0 + k s, and t = ln(v(s) / v0) / k+ const k = span > 0 ? (v1 - v0) / span : 0+ const s = Math.abs(k) < 1e-9 ? t * v0 : (v0 * (Math.exp(k * t) - 1)) / k+ return ps[i].at * source + Math.min(span, s)+ }+ return source+}++/** The speed at each of `n` places along the clip's own time (the line drawn over the clip, TL6b). */+export function profile(curve: SpeedPoint[], source: number, n: number): number[] {+ const ps = points(curve), total = played(curve, source)+ return Array.from({ length: n }, (_, i) => {+ const at = source > 0 ? sourceAt(curve, source, (total * i) / Math.max(1, n - 1)) / source : 0+ const j = Math.max(0, ps.findIndex((p) => p.at > at) - 1)+ const a = ps[j], b = ps[Math.min(ps.length - 1, j + 1)]+ return b.at > a.at ? a.speed + ((b.speed - a.speed) * (at - a.at)) / (b.at - a.at) : a.speed+ })+}diff --git a/sdk/timeline/test/keys.test.ts b/sdk/timeline/test/keys.test.tsnew file mode 100644index 00000000..8bf73d2b--- /dev/null+++ b/sdk/timeline/test/keys.test.ts@@ -0,0 +1,82 @@+import { describe, expect, test } from "bun:test"+import { bezier, CURVES, eased, EASES, played, profile, snap, snapMove, sourceAt, targets, timecode, valueAt, empty } from "../src"++describe("TL5: keys and easing", () => {+ test("between two keys the value follows the first key's ease; outside them it holds", () => {+ const keys = [{ at: 10, value: 0 }, { at: 30, value: 100 }]+ expect([0, 10, 20, 30, 99].map((f) => valueAt(keys, f))).toEqual([0, 0, 50, 100, 100])+ expect(valueAt([{ at: 10, value: 0, ease: "hold" }, { at: 30, value: 100 }], 29)).toBe(0)+ expect(valueAt([{ at: 0, value: [0, 0] }, { at: 10, value: [100, 50] }], 5)).toEqual([50, 25])+ expect(valueAt([{ at: 0, value: "red" }, { at: 10, value: "blue" }], 5)).toBe("red")+ expect(valueAt(undefined, 5)).toBeUndefined()+ })++ test("a cubic bezier is CSS's: its ends fixed, ease in-out through the middle, ease out ahead of linear", () => {+ const io = bezier(0.42, 0, 0.58, 1)+ expect(io(0)).toBe(0)+ expect(io(1)).toBe(1)+ expect(io(0.5)).toBeCloseTo(0.5, 4)+ expect(io(0.25)).toBeCloseTo(0.1292, 3)+ expect(eased(EASES["ease out"], 0.5)).toBeGreaterThan(0.5)+ expect(eased(EASES["ease in"], 0.5)).toBeLessThan(0.5)+ // a handle above 1 overshoots, as a curve dragged by hand can+ expect(Math.max(...Array.from({ length: 50 }, (_, i) => bezier(0.3, 1.6, 0.6, 1)(i / 49)))).toBeGreaterThan(1)+ // every x has one y, even where the curve is steep+ const steep = bezier(0, 1, 1, 0)+ for (let i = 1; i < 20; i++) expect(Number.isFinite(steep(i / 20))).toBe(true)+ })+})++describe("TL6b: a speed curve", () => {+ test("a flat curve is a constant speed", () => {+ const twice = [{ at: 0, speed: 2 }, { at: 1, speed: 2 }]+ expect(played(twice, 60)).toBeCloseTo(30)+ expect(sourceAt(twice, 60, 15)).toBeCloseTo(30)+ })++ test("the source frame at a time and the time a curve takes agree", () => {+ for (const [name, curve] of Object.entries(CURVES)) {+ const total = played(curve, 300)+ expect(sourceAt(curve, 300, total)).toBeCloseTo(300, 3)+ let before = -1+ for (let i = 0; i <= 20; i++) {+ const s = sourceAt(curve, 300, (total * i) / 20)+ expect(s, name).toBeGreaterThan(before)+ before = s+ }+ }+ // speeds stay in 0.1x to 10x whatever is asked+ expect(played([{ at: 0, speed: 1000 }, { at: 1, speed: 1000 }], 100)).toBeCloseTo(10)+ // the line drawn over a Bullet clip dips to its slow middle (0.3x) and stays in range+ const line = profile(CURVES.bullet, 300, 200)+ expect(Math.min(...line)).toBeLessThan(0.4)+ expect(Math.min(...line)).toBeGreaterThanOrEqual(0.3)+ expect(Math.max(...line)).toBeLessThanOrEqual(5)+ })+})++describe("TL4b: snapping, and TL0a: timecodes", () => {+ const t = { ...empty(30), markers: [{ id: "m", at: 200 }], tracks: [{ id: "main", kind: "main" as const, clips: [{ id: "a", kind: "video", start: 0, length: 90 }, { id: "b", kind: "video", start: 90, length: 60 }] }] }++ test("an edge snaps to the nearest clip edge, marker, beat or the playhead within reach, and says which", () => {+ const to = targets(t, { not: ["b"], playhead: 120, beats: [45] })+ expect(snap(93, to, 4)).toEqual({ frame: 90, to: { at: 90, what: "clip" } })+ expect(snap(118, to, 4).to?.what).toBe("playhead")+ expect(snap(47, to, 4).to?.what).toBe("beat")+ expect(snap(197, to, 4).to?.what).toBe("marker")+ expect(snap(160.4, to, 4)).toEqual({ frame: 160 })+ // a clip being moved doesn't snap to itself+ expect(to.some((x) => x.at === 150)).toBe(false)+ })++ test("a moved clip snaps by whichever edge is nearer a target", () => {+ const to = targets(t, { not: ["b"] })+ expect(snapMove(92, 60, to, 4)).toEqual({ by: -2, to: { at: 90, what: "clip" } })+ expect(snapMove(142, 60, to, 4).by).toBe(-2) // its end, at 202, to the marker at 200+ expect(snapMove(300, 60, to, 4)).toEqual({ by: 0 })+ })++ test("a timecode is drawn from frames", () => {+ expect([0, 29, 30, 1799, 1800, 4567].map((f) => timecode(f, 30))).toEqual(["00:00:00", "00:00:29", "00:01:00", "00:59:29", "01:00:00", "02:32:07"])+ })+})diff --git a/sdk/timeline/test/ops.test.ts b/sdk/timeline/test/ops.test.tsnew file mode 100644index 00000000..3740d31f--- /dev/null+++ b/sdk/timeline/test/ops.test.ts@@ -0,0 +1,163 @@+import { describe, expect, test } from "bun:test"+import { apply, applyAll, type Clip, empty, find, length, type Op, type Timeline, valueAt } from "../src"++const clip = (id: string, start: number, len: number, more: Partial<Clip> = {}): Clip => ({ id, kind: "video", start, length: len, ...more })+/** a main track of three clips (a 0-30, b 30-90, c 90-120), a title over b, music under all of it */+const film = (): Timeline => ({+ ...empty(30),+ tracks: [+ { id: "text-1", kind: "text", clips: [clip("title", 40, 30, { kind: "text" })] },+ { id: "main", kind: "main", clips: [clip("a", 0, 30, { in: 0, source: 300 }), clip("b", 30, 60, { in: 10, source: 300 }), clip("c", 90, 30, { in: 0, source: 30 })] },+ { id: "sound-1", kind: "sound", clips: [clip("music", 0, 120, { kind: "audio", in: 0, source: 900 })] },+ ],+})+const done = (t: Timeline, op: Op) => {+ const r = apply(t, op)+ if (!r.ok) throw new Error(r.why)+ return r.timeline+}+const at = (t: Timeline, id: string) => find(t, id)!.clip+const spans = (t: Timeline, track: string) => t.tracks.find((k) => k.id === track)!.clips.map((c) => `${c.id} ${c.start}-${c.start + c.length}`)++describe("TL0b: an operation is a pure function with an inverse", () => {+ const ops: Op[] = [+ { op: "move", ids: ["b"], by: 70 },+ { op: "trim", id: "b", edge: "start", to: 40 },+ { op: "trim", id: "a", edge: "end", to: 20 },+ { op: "split", at: 60 },+ { op: "remove", ids: ["a"] },+ { op: "cut", id: "b", side: "left", at: 50 },+ { op: "duplicate", ids: ["c"] },+ { op: "set", id: "b", set: { speed: 2 } },+ { op: "key", id: "b", prop: "scale", at: 10, value: 1.2 },+ { op: "mark", marker: { id: "m1", at: 45 } },+ { op: "track", id: "sound-1", set: { muted: true } },+ { op: "transition", transition: { id: "x1", kind: "dissolve", after: "a", length: 12 } },+ { op: "option", set: { magnet: false } },+ ]+ for (const op of ops)+ test(`${op.op} and its inverse give the timeline back`, () => {+ const t = film()+ const frozen = JSON.stringify(t)+ const r = apply(t, op)+ if (!r.ok) throw new Error(r.why)+ expect(JSON.stringify(t)).toBe(frozen)+ const back = apply(r.timeline, r.inverse)+ expect(back.ok && JSON.stringify(back.timeline)).toBe(frozen)+ })++ test("an operation that can't apply is refused with its reason", () => {+ const locked = done(film(), { op: "track", id: "main", set: { locked: true } })+ expect(apply(locked, { op: "move", ids: ["a"], by: 10 })).toEqual({ ok: false, why: "that track is locked" })+ expect(apply(film(), { op: "split", at: 500 })).toEqual({ ok: false, why: "no clip is under the playhead" })+ const coded = { ...film(), tracks: film().tracks.map((k) => ({ ...k, clips: k.clips.map((c) => (c.id === "a" ? { ...c, name: "Hook", locked: "set in code" } : c)) })) }+ expect(apply(coded, { op: "trim", id: "a", edge: "end", to: 10 })).toEqual({ ok: false, why: "Hook is set in code" })+ })++ test("several operations stop at the first refused, with the inverses of those made", () => {+ const r = applyAll(film(), [{ op: "split", at: 60 }, { op: "remove", ids: ["nope"] }, { op: "remove", ids: ["a"] }])+ expect(r.refused?.why).toBe("there is no clip nope")+ expect(r.inverse.length).toBe(1)+ expect(spans(r.timeline, "main")).toEqual(["a 0-30", "b 30-60", "b+ 60-90", "c 90-120"])+ })+})++describe("TL3: clips", () => {+ test("a trimmed edge moves the clip's place in its source, never past the source's ends, and comes back out", () => {+ const t = done(film(), { op: "option", set: { magnet: false } })+ const inward = done(t, { op: "trim", id: "b", edge: "start", to: 45 })+ expect(at(inward, "b")).toMatchObject({ start: 45, length: 45, in: 25 })+ // b's source starts 10 frames before it: it backs out to frame 30 - 10 = 20 at most (a ends at 30 on its track)+ expect(at(done(inward, { op: "trim", id: "b", edge: "start", to: 0 }), "b")).toMatchObject({ start: 30, in: 10 })+ // c has 30 frames of source in all: its end can't go past 120+ expect(at(done(t, { op: "trim", id: "c", edge: "end", to: 500 }), "c").length).toBe(30)+ expect(at(done(t, { op: "trim", id: "a", edge: "end", to: 0 }), "a").length).toBe(1)+ })++ test("a split writes the clip twice, meeting at the cut, the right half on in its source", () => {+ const t = done(film(), { op: "split", at: 60, ids: ["b"] })+ expect(spans(t, "main")).toEqual(["a 0-30", "b 30-60", "b+ 60-90", "c 90-120"])+ expect(at(t, "b+").in).toBe(40)+ // with none named, every clip under the playhead: the title and the music too+ const all = done(film(), { op: "split", at: 60 })+ expect(spans(all, "text-1")).toEqual(["title 40-60", "title+ 60-70"])+ expect(spans(all, "sound-1")).toEqual(["music 0-60", "music+ 60-120"])+ })++ test("a split clip's keys stay at their frames, with the value at the cut on both halves", () => {+ let t = done(film(), { op: "key", id: "b", prop: "scale", at: 0, value: 1 })+ t = done(t, { op: "key", id: "b", prop: "scale", at: 40, value: 2 })+ t = done(t, { op: "split", at: 50, ids: ["b"] })+ expect(at(t, "b").keys!.scale).toEqual([{ at: 0, value: 1 }, { at: 20, value: 1.5 }])+ expect(at(t, "b+").keys!.scale).toEqual([{ at: 0, value: 1.5 }, { at: 20, value: 2 }])+ expect(valueAt(at(t, "b+").keys!.scale, 10)).toBe(1.75)+ })++ test("Q removes what is left of the playhead on a clip, W what is right, the gap closed", () => {+ const q = done(film(), { op: "cut", id: "b", side: "left", at: 50 })+ expect(spans(q, "main")).toEqual(["a 0-30", "b 30-70", "c 70-100"])+ expect(at(q, "b").in).toBe(30)+ const w = done(film(), { op: "cut", id: "b", side: "right", at: 50 })+ expect(spans(w, "main")).toEqual(["a 0-30", "b 30-50", "c 50-80"])+ // on a track with no magnet the later clips still close up+ const two = { ...film(), tracks: [{ id: "sound-1", kind: "sound" as const, clips: [clip("x", 0, 60), clip("y", 60, 30)] }] }+ expect(spans(done(two, { op: "cut", id: "x", side: "right", at: 20 }), "sound-1")).toEqual(["x 0-20", "y 20-50"])+ })++ test("duplicate puts a copy after the clip", () => {+ expect(spans(done(film(), { op: "duplicate", ids: ["a"] }), "main")).toEqual(["a 0-30", "a+ 30-60", "b 60-120", "c 120-150"])+ })+})++describe("TL4: the magnet and linkage", () => {+ test("with the magnet on the main track has no gap: a removed clip's gap closes", () => {+ const t = done(film(), { op: "remove", ids: ["a"] })+ expect(spans(t, "main")).toEqual(["b 0-60", "c 60-90"])+ expect(length(t)).toBe(120) // the music is still 120 long+ })++ test("a clip dragged past its neighbour's middle swaps places with it", () => {+ // a (0-30) dragged 40 later: its middle (55) is short of b's (60), so nothing swaps; 50 later it is past+ expect(spans(done(film(), { op: "move", ids: ["a"], by: 40 }), "main")).toEqual(["a 0-30", "b 30-90", "c 90-120"])+ expect(spans(done(film(), { op: "move", ids: ["a"], by: 50 }), "main")).toEqual(["b 0-60", "a 60-90", "c 90-120"])+ })++ test("with the magnet off a gap is allowed, and a clip dropped over another goes to a track above", () => {+ const off = done(film(), { op: "option", set: { magnet: false } })+ expect(spans(done(off, { op: "remove", ids: ["a"] }), "main")).toEqual(["b 30-90", "c 90-120"])+ const over = done(off, { op: "move", ids: ["c"], by: -50 })+ expect(over.tracks.map((k) => k.id)).toEqual(["text-1", "overlay-1", "main", "sound-1"])+ expect(spans(over, "overlay-1")).toEqual(["c 40-70"])+ })++ test("what sits over a main clip moves and goes with it; with linkage off it stays", () => {+ // the title starts at 40, inside b (30-90): removing a moves b 30 earlier, and the title with it+ expect(spans(done(film(), { op: "remove", ids: ["a"] }), "text-1")).toEqual(["title 10-40"])+ expect(done(film(), { op: "remove", ids: ["b"] }).tracks.find((k) => k.id === "text-1")!.clips).toEqual([])+ const unlinked = done(film(), { op: "option", set: { linkage: false } })+ expect(spans(done(unlinked, { op: "remove", ids: ["a"] }), "text-1")).toEqual(["title 40-70"])+ // sound is never carried+ expect(spans(done(film(), { op: "remove", ids: ["a"] }), "sound-1")).toEqual(["music 0-120"])+ })++ test("a transition stays on its cut as the cut moves, and goes when the cut does", () => {+ const t = done(film(), { op: "transition", transition: { id: "x", kind: "dissolve", after: "b", length: 500 } })+ expect(t.transitions).toEqual([{ id: "x", kind: "dissolve", after: "b", length: 30 }])+ expect(done(t, { op: "remove", ids: ["a"] }).transitions.length).toBe(1)+ expect(done(t, { op: "remove", ids: ["c"] }).transitions).toEqual([])+ })+})++describe("TL6: speed", () => {+ test("a clip's length follows its speed, and the magnet closes the gap", () => {+ const t = done(film(), { op: "set", id: "b", set: { speed: 2 } })+ expect(spans(t, "main")).toEqual(["a 0-30", "b 30-60", "c 60-90"])+ expect(apply(film(), { op: "set", id: "b", set: { speed: 0 } })).toEqual({ ok: false, why: "a speed is more than 0" })+ })++ test("a curve's length is the time its source takes, and taking it off gives the length back", () => {+ const t = done(film(), { op: "set", id: "b", set: { curve: [{ at: 0, speed: 2 }, { at: 1, speed: 2 }] } })+ expect(at(t, "b").length).toBe(30)+ expect(at(done(t, { op: "set", id: "b", set: { curve: null } }), "b").length).toBe(60)+ })+})diff --git a/sdk/timeline/tsconfig.json b/sdk/timeline/tsconfig.jsonnew file mode 100644index 00000000..65e973e6--- /dev/null+++ b/sdk/timeline/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["bun"] }, "include": ["src", "test"] }