Skip to content

armgit / raea

Public Imported from GitHub
0

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.

TL10: in progress: what the frame store decides, in sdk/timeline cache.ts

shinyobjectz47cf338cd67e
diff --git a/sdk/timeline/src/cache.ts b/sdk/timeline/src/cache.ts
new file mode 100644
index 00000000..1d78c614
--- /dev/null
+++ b/sdk/timeline/src/cache.ts
@@ -0,0 +1,110 @@
+// The frames kept while editing (docs/timeline.feature TL10): which ranges an edit changed (so only those are drawn
+// again, TL10c), what a kept range is kept under (TL10b), and what goes first when the store is over its size
+// (TL10e). Pure: the stage that draws frames and the store that holds them use these to decide.
+import { type Clip, end, type Frames, type Timeline, type Track } from "./model"
+
+export type Range = [from: Frames, to: Frames]
+
+/** Ranges in order, touching and overlapping ones joined, empty ones dropped. */
+export function joined(ranges: Range[]): Range[] {
+ const out: Range[] = []
+ for (const [a, b] of [...ranges].filter(([a, b]) => b > a).sort((x, y) => x[0] - y[0])) {
+ const last = out[out.length - 1]
+ if (last && a <= last[1]) last[1] = Math.max(last[1], b)
+ else out.push([a, b])
+ }
+ return out
+}
+
+/** `ranges` with `cut` taken out of them. */
+export function without(ranges: Range[], cut: Range[]): Range[] {
+ let out = joined(ranges)
+ for (const [c0, c1] of joined(cut)) out = out.flatMap(([a, b]): Range[] => (c1 <= a || c0 >= b ? [[a, b]] : [[a, Math.min(b, c0)], [Math.max(a, c1), b]])).filter(([a, b]) => b > a)
+ return out
+}
+
+const drawn = (k: Track, c: Clip) => !c.off && !(k.kind === "sound" ? k.muted : k.hidden)
+/** What a clip draws, said so that the same pictures give the same words wherever the clip is cut: a media clip
+ * by where its source sits against the timeline (so the two halves of a split say what the whole did), anything
+ * else by where it starts (its content runs from its own first frame). Keys and fades are said at their timeline
+ * frames. Its name, its lock and its group aren't in it. */
+function look(k: Track, n: number, c: Clip): string {
+ const still = c.in !== undefined && !c.curve
+ const phase = still ? `p${c.in! - c.start * (c.speed && c.speed > 0 ? c.speed : 1)}` : `s${c.start}+${c.length}`
+ const keys = Object.entries(c.keys ?? {}).map(([p, ks]) => [p, ks.map((x) => [x.at + c.start, x.value, x.ease ?? "linear"])])
+ const fades = [c.fadeIn ? [c.start, c.fadeIn] : 0, c.fadeOut ? [end(c), c.fadeOut] : 0]
+ return JSON.stringify([n, k.kind, c.kind, phase, c.speed ?? 1, c.curve ?? null, c.shows ?? null, c.props ?? null, keys, c.volume ?? 1, fades, c.at ?? null])
+}
+
+/** Every drawn thing on the timeline as the span it covers and what it draws there. */
+function spans(t: Timeline): { span: Range; look: string }[] {
+ const out: { span: Range; look: string }[] = []
+ t.tracks.forEach((k, n) => {
+ for (const c of k.clips) if (drawn(k, c)) out.push({ span: [c.start, end(c)], look: look(k, n, c) })
+ })
+ for (const x of t.transitions) {
+ const c = t.tracks.flatMap((k) => k.clips).find((o) => o.id === x.after)
+ const half = Math.ceil(x.length / 2)
+ if (c) out.push({ span: [end(c) - half, end(c) + half], look: `x:${x.kind}:${x.length}:${end(c)}` })
+ }
+ return out
+}
+
+/** The frames whose picture or sound differ between two states of a timeline: wherever what is drawn over a frame
+ * isn't what was. Moving a clip from 2:00-2:05 to 2:10-2:15 gives those two ranges and nothing else (TL10c); a
+ * split of footage gives none. */
+export function changed(before: Timeline, after: Timeline): Range[] {
+ const a = spans(before), b = spans(after)
+ const edges = [...new Set([...a, ...b].flatMap((x) => x.span))].sort((x, y) => x - y)
+ const over = (xs: { span: Range; look: string }[], from: Frames, to: Frames) => xs.filter((x) => x.span[0] < to && x.span[1] > from).map((x) => x.look).sort().join("\n")
+ const out: Range[] = []
+ for (let i = 0; i + 1 < edges.length; i++) if (over(a, edges[i], edges[i + 1]) !== over(b, edges[i], edges[i + 1])) out.push([edges[i], edges[i + 1]])
+ return joined(out)
+}
+
+/** What a range of kept frames is kept under: everything that draws it. Two states of a timeline that draw the
+ * range the same give the same key, so frames drawn before an edit elsewhere (or before an undo) are found again. */
+export function keyOf(t: Timeline, [from, to]: Range, media: (clip: Clip) => string = () => ""): string {
+ const parts: string[] = [`${t.fps}`]
+ t.tracks.forEach((k, n) => {
+ for (const c of k.clips) if (drawn(k, c) && c.start < to && end(c) > from) parts.push(`${look(k, n, c)}:${media(c)}`)
+ })
+ for (const x of spans(t)) if (x.look.startsWith("x:") && x.span[0] < to && x.span[1] > from) parts.push(x.look)
+ // FNV-1a over the parts: a short name for a file, not a secret
+ let h = 0x811c9dc5
+ for (const ch of parts.sort().join("|")) h = Math.imul(h ^ ch.charCodeAt(0), 0x01000193) >>> 0
+ return `${from}-${to}-${h.toString(16).padStart(8, "0")}`
+}
+
+export interface Kept {
+ key: string
+ bytes: number
+ /** when it was last played (ms) */
+ used: number
+ /** it belongs to a version that was closed or discarded: it goes at once */
+ stale?: boolean
+}
+
+/** The keys to drop so the store is at most `limit` bytes: stale ones first, then the least recently played. What
+ * is under the playhead (`hold`) stays while anything else can go (TL10e). */
+export function evict(kept: Kept[], limit: number, hold: Set<string> = new Set()): string[] {
+ let total = kept.reduce((n, k) => n + k.bytes, 0)
+ const out: string[] = []
+ const order = [...kept].sort((a, b) => Number(!!b.stale) - Number(!!a.stale) || Number(hold.has(a.key)) - Number(hold.has(b.key)) || a.used - b.used)
+ for (const k of order) {
+ if (!k.stale && total <= limit) break
+ out.push(k.key)
+ total -= k.bytes
+ }
+ return out
+}
+
+/** The ranges to draw next while there is time (TL10d): what isn't kept from the playhead on, nearest first, each
+ * at most `chunk` frames, then what is before it. */
+export function ahead(length: Frames, kept: Range[], playhead: Frames, chunk: Frames): Range[] {
+ const missing = without([[0, length]], kept)
+ const pieces = missing.flatMap(([a, b]): Range[] => Array.from({ length: Math.ceil((b - a) / chunk) }, (_, i) => [a + i * chunk, Math.min(b, a + (i + 1) * chunk)] as Range))
+ const after = pieces.filter(([, b]) => b > playhead).sort((x, y) => x[0] - y[0])
+ const before = pieces.filter(([, b]) => b <= playhead).sort((x, y) => y[0] - x[0])
+ return [...after, ...before]
+}
diff --git a/sdk/timeline/src/index.ts b/sdk/timeline/src/index.ts
index e34c6ec3..16274f79 100644
--- a/sdk/timeline/src/index.ts
+++ b/sdk/timeline/src/index.ts
@@ -6,3 +6,4 @@ export * from "./keys"
export * from "./speed"
export * from "./snap"
export * from "./read"
+export * from "./cache"
diff --git a/sdk/timeline/test/cache.test.ts b/sdk/timeline/test/cache.test.ts
new file mode 100644
index 00000000..9aa8fa62
--- /dev/null
+++ b/sdk/timeline/test/cache.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, test } from "bun:test"
+import { ahead, apply, changed, type Clip, empty, evict, joined, keyOf, type Timeline, without } from "../src"
+
+const clip = (id: string, start: number, len: number, more: Partial<Clip> = {}): Clip => ({ id, kind: "video", start, length: len, ...more })
+const film = (): Timeline => ({
+ ...empty(30),
+ magnet: false,
+ tracks: [
+ { id: "overlay-1", kind: "overlay", clips: [clip("logo", 3600, 150)] },
+ { id: "main", kind: "main", clips: [clip("a", 0, 3000), clip("b", 3000, 3000)] },
+ { id: "sound-1", kind: "sound", clips: [clip("music", 0, 6000, { kind: "audio" })] },
+ ],
+})
+const done = (t: Timeline, op: Parameters<typeof apply>[1]) => {
+ const r = apply(t, op)
+ if (!r.ok) throw new Error(r.why)
+ return r.timeline
+}
+
+describe("TL10c: an edit drops only what it changed", () => {
+ test("a clip moved from 2:00-2:05 to 2:10-2:15 changes those two ranges and nothing else", () => {
+ const t = film()
+ expect(changed(t, done(t, { op: "move", ids: ["logo"], by: 300 }))).toEqual([[3600, 3750], [3900, 4050]])
+ })
+
+ test("a key, a hidden track and a transition change the spans they draw; a name, a lock and a marker change nothing", () => {
+ const t = film()
+ expect(changed(t, done(t, { op: "key", id: "logo", prop: "scale", at: 10, value: 2 }))).toEqual([[3600, 3750]])
+ expect(changed(t, done(t, { op: "track", id: "overlay-1", set: { hidden: true } }))).toEqual([[3600, 3750]])
+ expect(changed(t, done(t, { op: "track", id: "sound-1", set: { muted: true } }))).toEqual([[0, 6000]])
+ expect(changed(t, done(t, { op: "transition", transition: { id: "x", kind: "dissolve", after: "a", length: 30 } }))).toEqual([[2985, 3015]])
+ expect(changed(t, done(t, { op: "set", id: "a", set: { name: "Opening" } }))).toEqual([])
+ expect(changed(t, done(t, { op: "track", id: "main", set: { locked: true, height: 80 } }))).toEqual([])
+ expect(changed(t, done(t, { op: "mark", marker: { id: "m", at: 100 } }))).toEqual([])
+ })
+
+ test("a split of footage draws the same frames: nothing is drawn again; a split of anything else restarts its right half", () => {
+ const footage: Timeline = { ...film(), tracks: [{ id: "main", kind: "main", clips: [clip("a", 0, 3000, { in: 0, source: 9000 })] }] }
+ expect(changed(footage, done(footage, { op: "split", at: 1000, ids: ["a"] }))).toEqual([])
+ // and one half deleted changes only that half (the magnet off: the other stays put)
+ const cut = done(done(footage, { op: "split", at: 1000, ids: ["a"] }), { op: "remove", ids: ["a"] })
+ expect(changed(footage, cut)).toEqual([[0, 1000]])
+ const t = film()
+ expect(changed(t, done(t, { op: "split", at: 1000, ids: ["a"] }))).toEqual([[0, 3000]])
+ })
+
+ test("a range's key is the same for two states that draw it the same, and differs when they don't", () => {
+ const t = film()
+ const moved = done(t, { op: "move", ids: ["logo"], by: 300 })
+ expect(keyOf(moved, [0, 3000])).toBe(keyOf(t, [0, 3000]))
+ expect(keyOf(moved, [3600, 3750])).not.toBe(keyOf(t, [3600, 3750]))
+ // undone: the frames kept before the edit are found again
+ expect(keyOf(done(moved, { op: "move", ids: ["logo"], by: -300 }), [3600, 3750])).toBe(keyOf(t, [3600, 3750]))
+ // the same clip over other media is another picture
+ expect(keyOf(t, [0, 3000], () => "v2")).not.toBe(keyOf(t, [0, 3000], () => "v1"))
+ })
+})
+
+describe("TL10d, TL10e: what is drawn next, and what goes first", () => {
+ test("ranges join, and one taken out of another leaves the rest", () => {
+ expect(joined([[10, 20], [0, 5], [5, 10], [30, 30], [18, 25]])).toEqual([[0, 25]])
+ expect(without([[0, 100]], [[20, 30], [90, 120]])).toEqual([[0, 20], [30, 90]])
+ })
+
+ test("from the playhead on first, nearest first, then what is behind it", () => {
+ expect(ahead(300, [[100, 160]], 120, 60)).toEqual([[160, 220], [220, 280], [280, 300], [60, 100], [0, 60]])
+ expect(ahead(300, [[0, 300]], 0, 60)).toEqual([])
+ })
+
+ test("a closed version's frames go at once, then the least recently played, never what is under the playhead while anything else can go", () => {
+ const kept = [
+ { key: "old", bytes: 40, used: 1 },
+ { key: "here", bytes: 40, used: 2 },
+ { key: "recent", bytes: 40, used: 9 },
+ { key: "closed", bytes: 10, used: 8, stale: true },
+ ]
+ expect(evict(kept, 1000)).toEqual(["closed"])
+ expect(evict(kept, 90, new Set(["here"]))).toEqual(["closed", "old"])
+ expect(evict(kept, 30, new Set(["here"]))).toEqual(["closed", "old", "recent", "here"])
+ })
+})