Skip to content

Open source CapCut alternative.

TypeScript

feat(site): estimate smoothed slow-motion frames in the tab export with RIFE on WebGPU

David Le44216ad5028d
diff --git a/site/.gitignore b/site/.gitignore
index c8a65ecb..0fcb3f8a 100644
--- a/site/.gitignore
+++ b/site/.gitignore
@@ -59,3 +59,5 @@ next-env.d.ts
# MediaPipe wasm runtime, staged from node_modules by postinstall
/public/mediapipe/wasm/
/public/cut-fonts/
+/public/models/rife_v4.25.onnx
+/public/ort/
diff --git a/site/package-lock.json b/site/package-lock.json
index 504a9306..0147e057 100644
--- a/site/package-lock.json
+++ b/site/package-lock.json
@@ -51,6 +51,7 @@
"mediabunny": "^1.55.5",
"next": "16.3.4",
"node-web-audio-api": "^2.2.0",
+ "onnxruntime-web": "1.29.0",
"openai": "^6.39.0",
"pg": "^8.20.0",
"posthog-js": "^1.428.5",
@@ -77,6 +78,7 @@
"@types/pg": "^8.20.0",
"@types/react": "^19",
"@types/react-dom": "^19",
+ "7z-wasm": "1.2.0",
"bun": "^1.3.14",
"dotenv": "^17.4.2",
"dotenv-cli": "^11.0.0",
@@ -7353,6 +7355,22 @@
"dev": true,
"license": "BSD-2-Clause"
},
+ "node_modules/7z-wasm": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/7z-wasm/-/7z-wasm-1.2.0.tgz",
+ "integrity": "sha512-AZjtWXFleAe5nQ27JYISs70cICjO0zZr4LU45I9pXKcrhG0qiEWgq3Vjwr9JHHihFLuqgc7uSHYVn/z3vXCjdw==",
+ "dev": true,
+ "license": "SEE LICENSE IN License.txt",
+ "dependencies": {
+ "readline-sync": "^1.4.10"
+ },
+ "bin": {
+ "7z-wasm": "bin/cli"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/accepts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -10952,6 +10970,12 @@
"node": ">=16"
}
},
+ "node_modules/flatbuffers": {
+ "version": "25.9.23",
+ "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz",
+ "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==",
+ "license": "Apache-2.0"
+ },
"node_modules/flatted": {
"version": "3.4.2",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
@@ -11471,6 +11495,12 @@
"node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0"
}
},
+ "node_modules/guid-typescript": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz",
+ "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==",
+ "license": "ISC"
+ },
"node_modules/has-bigints": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",
@@ -14957,6 +14987,26 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/onnxruntime-common": {
+ "version": "1.29.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.29.0.tgz",
+ "integrity": "sha512-/F63/e2VJoaVXGGNu6S5QH7jivBThGO95OzAVXXQ8hTta/b1QxI8udHa6cI3+3mAb5WWIIaMMwfZw01oivjJ1g==",
+ "license": "MIT"
+ },
+ "node_modules/onnxruntime-web": {
+ "version": "1.29.0",
+ "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.29.0.tgz",
+ "integrity": "sha512-LuQlpX6MFLJZu756erwUeb1mNfoJGbs1kzDwJGNlf5RvfYMdqhcY3vNpDPK40CUV2HoWTkIj+uS0o36GFHjeYw==",
+ "license": "MIT",
+ "dependencies": {
+ "flatbuffers": "^25.1.24",
+ "guid-typescript": "^1.0.9",
+ "long": "^5.2.3",
+ "onnxruntime-common": "1.29.0",
+ "platform": "^1.3.6",
+ "protobufjs": "^7.2.4"
+ }
+ },
"node_modules/open": {
"version": "11.0.0",
"resolved": "https://registry.npmjs.org/open/-/open-11.0.0.tgz",
@@ -15556,6 +15606,12 @@
"pathe": "^2.0.3"
}
},
+ "node_modules/platform": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz",
+ "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==",
+ "license": "MIT"
+ },
"node_modules/playwright": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
@@ -16319,6 +16375,16 @@
"url": "https://paulmillr.com/funding/"
}
},
+ "node_modules/readline-sync": {
+ "version": "1.4.10",
+ "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz",
+ "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
"node_modules/recast": {
"version": "0.23.11",
"resolved": "https://registry.npmjs.org/recast/-/recast-0.23.11.tgz",
diff --git a/site/package.json b/site/package.json
index 0bf08127..48dcffcb 100644
--- a/site/package.json
+++ b/site/package.json
@@ -12,7 +12,7 @@
"build": "next build",
"start": "next start",
"lint": "node --max-old-space-size=8192 node_modules/eslint/bin/eslint.js",
- "postinstall": "patch-package && node scripts/check-mediabunny-patch.mjs && prisma generate && node scripts/copy-mediapipe-assets.mjs && node scripts/fetch-cut-fonts.mjs",
+ "postinstall": "patch-package && node scripts/check-mediabunny-patch.mjs && prisma generate && node scripts/copy-mediapipe-assets.mjs && node scripts/fetch-cut-fonts.mjs && node scripts/stage-frame-synth.mjs",
"db:generate": "prisma generate",
"db:pull": "prisma db pull",
"prisma:dev": "dotenv -e .env.development -- npx prisma migrate dev",
@@ -74,6 +74,7 @@
"mediabunny": "^1.55.5",
"next": "16.3.4",
"node-web-audio-api": "^2.2.0",
+ "onnxruntime-web": "1.29.0",
"openai": "^6.39.0",
"pg": "^8.20.0",
"posthog-js": "^1.428.5",
@@ -100,6 +101,7 @@
"@types/pg": "^8.20.0",
"@types/react": "^19",
"@types/react-dom": "^19",
+ "7z-wasm": "1.2.0",
"bun": "^1.3.14",
"dotenv": "^17.4.2",
"dotenv-cli": "^11.0.0",
diff --git a/site/scripts/stage-frame-synth.mjs b/site/scripts/stage-frame-synth.mjs
new file mode 100644
index 00000000..f1735db5
--- /dev/null
+++ b/site/scripts/stage-frame-synth.mjs
@@ -0,0 +1,81 @@
+// Stage what smooth slow motion runs on in the tab: the RIFE frame
+// interpolation model and the ONNX Runtime WebGPU build that executes it.
+// Both are served from public/ so the page fetches nothing from a third
+// party at run time.
+//
+// The model is Practical-RIFE 4.25 (MIT), in the ONNX export the vs-mlrt
+// project publishes as a 7z archive. The archive is fetched once, checked
+// against its pinned digest, and the fp32 graph inside it is unpacked here.
+// The runtime's wasm pair is copied from node_modules on install; it is
+// ~28MB, so it is staged like the MediaPipe runtime is, never committed.
+//
+// Files already staged are kept, so a re-install is free and an offline one
+// keeps working. Runs from postinstall. A model that cannot be staged fails
+// the install: the page picks the network whenever the machine has WebGPU,
+// and a build shipped without the file would fail every smoothed export
+// instead.
+import { createHash } from "node:crypto";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+
+const MODEL = {
+ url: "https://github.com/AmusementClub/vs-mlrt/releases/download/external-models/rife_v4.25.7z",
+ archiveSha256: "172fe975c1775134bb87108e4ec6d1a89e861cc5d3be2ac23bf08afe5ed626b8",
+ /** The member to unpack: the fp32 graph that takes its own padding. */
+ member: "rife/rife_v4.25.onnx",
+ sha256: "084f56a0c1e49f404d7a0a171b62a5d49078efdb02fea14d969069e604c60fe9",
+ /** Keep in step with frameSynth.ts, which fetches this path. */
+ dest: path.join(root, "public", "models", "rife_v4.25.onnx"),
+};
+
+const RUNTIME = {
+ src: path.join(root, "node_modules", "onnxruntime-web", "dist"),
+ /** Keep in step with frameSynth.ts, which points the runtime here. */
+ dest: path.join(root, "public", "ort"),
+ files: ["ort-wasm-simd-threaded.asyncify.mjs", "ort-wasm-simd-threaded.asyncify.wasm"],
+};
+
+const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
+
+async function stageModel() {
+ if (existsSync(MODEL.dest) && sha256(readFileSync(MODEL.dest)) === MODEL.sha256) return;
+ const res = await fetch(MODEL.url);
+ if (!res.ok) throw new Error(`${MODEL.url}: HTTP ${res.status}`);
+ const archive = new Uint8Array(await res.arrayBuffer());
+ const got = sha256(archive);
+ if (got !== MODEL.archiveSha256)
+ throw new Error(`${MODEL.url}: digest ${got}, expected ${MODEL.archiveSha256}`);
+ const { default: SevenZip } = await import("7z-wasm");
+ const sz = await SevenZip({ print: () => {}, printErr: () => {} });
+ const name = "rife.7z";
+ const stream = sz.FS.open(name, "w+");
+ sz.FS.write(stream, archive, 0, archive.length);
+ sz.FS.close(stream);
+ sz.callMain(["x", name, MODEL.member, "-y"]);
+ const model = sz.FS.readFile(MODEL.member);
+ const modelGot = sha256(model);
+ if (modelGot !== MODEL.sha256)
+ throw new Error(`${MODEL.member}: digest ${modelGot}, expected ${MODEL.sha256}`);
+ mkdirSync(path.dirname(MODEL.dest), { recursive: true });
+ writeFileSync(MODEL.dest, model);
+}
+
+function stageRuntime() {
+ if (!existsSync(RUNTIME.src)) {
+ console.warn("stage-frame-synth: onnxruntime-web not installed; skipping runtime");
+ return;
+ }
+ mkdirSync(RUNTIME.dest, { recursive: true });
+ for (const f of RUNTIME.files) copyFileSync(path.join(RUNTIME.src, f), path.join(RUNTIME.dest, f));
+}
+
+stageRuntime();
+try {
+ await stageModel();
+} catch (err) {
+ console.error(`stage-frame-synth: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+}
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index 90716a44..6ff74f39 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -38,10 +38,11 @@ import type { InputVideoTrack, WrappedCanvas } from "mediabunny";
import { allowance, canvasBytes, holdMemory } from "./memoryBudget";
import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
-import { applyEffectToCanvas, evalOverlayFrame, retimeOf, grainTile, isAudioEffect, isMaskAnimated, isOverlayAnimated, maskFrameAt, MATTE_FPS, matteLumaToAlpha, planAnimatedLayers, type LottieHandle, type OverlayAnim, type PaintPhase } from "@donkeycut/effects-kit";
+import { applyEffectToCanvas, evalOverlayFrame, retimeOf, grainTile, smoothsAt, isAudioEffect, isMaskAnimated, isOverlayAnimated, maskFrameAt, MATTE_FPS, matteLumaToAlpha, planAnimatedLayers, type LottieHandle, type OverlayAnim, type PaintPhase } from "@donkeycut/effects-kit";
import { backdropStill, loadBackdropStill } from "./backdropStills";
import { hasSubjectOverlays, SubjectMaskCompositor } from "./behindPass";
import { createRasterCanvas, type RasterSurface } from "./raster";
+import { exportFrameSynth, SYNTH_EDGE, synthWeight, type FrameSynth } from "./frameSynth";
import { renderElementPng } from "./textRender";
import { assetIsSilent, behindSubjectOverlay, clipCovers, frameOf, frontSubjectOverlay, isEffectOverlay, isTextOverlay, laneOf, overlayAnimStyle, projectBackground, projectFadeSeconds, rectOf, removalActive } from "./types";
import type { ClipAnim, ClipSpan, EffectOverlay, MediaAsset, Overlay, StickerOverlay } from "./types";
@@ -170,11 +171,19 @@ const READER_GRACE = 2;
const BACK_WINDOW_BYTES = 64 << 20;
const BACK_WINDOW_MAX = 12;
/** Canvases the reader's pools cycle, in frames: the forward pool plus the
- * backward window and the two frames a fill needs around it. */
+ * backward window, the frame it keeps beyond the ask, and the two a fill
+ * needs around it. */
export function readerPoolFrames(r: { backWindow: number }): number {
- return READER_POOL + (r.backWindow > 0 ? r.backWindow + 2 : 0);
+ return READER_POOL + (r.backWindow > 0 ? r.backWindow + 3 : 0);
}
+const frameOfWrapped = (wrapped: WrappedCanvas): Frame => ({
+ kind: "ready",
+ image: wrapped.canvas,
+ width: wrapped.canvas.width,
+ height: wrapped.canvas.height,
+});
+
/** A clip's source time at timeline time `t`. */
function sourceTimeAt(span: ClipSpan, t: number): number {
return retimeOf(span.clip).srcAt(Math.max(0, t - span.start));
@@ -280,22 +289,59 @@ export class ClipReader {
* source has none — a still-less video, or a time past its end. A render
* never reports `pending`: it waits for the decode instead of moving on. */
async frameAt(at: number): Promise<Frame> {
- let sink = await this.open();
if (this.still) return this.still;
- if (!sink) return MISSING_FRAME;
+ // A plain read cycles the pool past whatever pair was held.
+ this.pair = null;
+ const wrapped = await this.wrappedAt(at);
+ return wrapped ? frameOfWrapped(wrapped) : this.still ?? MISSING_FRAME;
+ }
+
+ /** The last pair handed out, kept while the asks stay between its two
+ * frames: an output frame between the same two sources costs no decode. */
+ private pair: { a: WrappedCanvas; b: WrappedCanvas | null } | null = null;
+
+ /**
+ * The source frames either side of `at`, for a clip smoothing its slow
+ * motion: `a` covers `at`, `b` is the next frame, or null at the end of the
+ * source. Asks walk forward like the plain read does — the pair advances by
+ * one decode when `at` passes `b`, and the frame that was `b` becomes `a`
+ * without being decoded again.
+ */
+ async pairAt(at: number): Promise<{ a: WrappedCanvas; b: WrappedCanvas | null } | null> {
+ if (this.still) return null;
+ const held = this.pair;
+ // A pair with no `b` is the source's last frame; it covers every ask
+ // from there on, so a render finishing on it never reads again.
+ if (held && at >= held.a.timestamp - 1e-4 && (!held.b || at < held.b.timestamp - 1e-4)) return held;
+ let a: WrappedCanvas | null;
+ if (held?.b && at >= held.b.timestamp - 1e-4 && at < held.b.timestamp + Math.max(held.b.duration, 1e-3) - 1e-4) {
+ a = held.b;
+ this.lastAt = at;
+ } else {
+ this.pair = null;
+ a = await this.wrappedAt(at);
+ }
+ if (!a) return null;
+ const b = await this.wrappedAt(a.timestamp + Math.max(a.duration, 1e-3));
+ this.pair = { a, b: b && b.timestamp > a.timestamp + 1e-4 ? b : null };
+ return this.pair;
+ }
+
+ /** The decoded frame covering source time `at`, null when the source has
+ * none there. Readers are rebuilt through decoder failures that pass. */
+ private async wrappedAt(at: number): Promise<WrappedCanvas | null> {
+ let sink = await this.open();
+ if (this.still || !sink) return null;
const stepBack = at < this.lastAt - 1e-6;
this.lastAt = at;
for (;;) {
try {
- const wrapped = (stepBack && (await this.backFrame(at))) || (await sink.getCanvas(Math.max(0, at)));
+ const wrapped =
+ this.heldBack(at) ||
+ (stepBack && (await this.backFrame(at))) ||
+ (await sink.getCanvas(Math.max(0, at)));
this.failStreak = 0;
- if (!wrapped) return MISSING_FRAME;
- return {
- kind: "ready",
- image: wrapped.canvas,
- width: wrapped.canvas.width,
- height: wrapped.canvas.height,
- };
+ return wrapped ?? null;
} catch (err) {
// Decoders die mid-job for reasons that pass: a signed link that
// expired under a long render (reopening resolves the URL again), a
@@ -328,41 +374,58 @@ export class ClipReader {
* source has no frame there, and the ordinary read answers.
*/
private async backFrame(at: number): Promise<WrappedCanvas | null> {
- const covering = (f: WrappedCanvas) =>
- f.timestamp <= at + 1e-4 && at < f.timestamp + Math.max(f.duration, 1e-4) + 1e-4;
- const held = this.backFrames.find(covering);
+ const held = this.heldBack(at);
if (held) return held;
if (!this.track) return null;
const kt = await keyframeTimeAt(this.track, Math.max(0, at));
if (kt === null) return null;
const window = this.windowFrames;
this.backSink ??= frameSink(this.track, undefined, {
- poolSize: window + 2,
+ poolSize: window + 3,
...(this.software ? { software: true } : {}),
});
const start = Math.max(kt, at - (window - 1) * this.frameDt, 0);
const frames: WrappedCanvas[] = [];
const stream = this.backSink.canvases(start);
+ // The window runs one frame past the ask: a clip smoothing its slow
+ // motion reads the frame after the one covering `at` as well, and that
+ // one beyond keeps the read inside the window.
+ let covered = false;
try {
for (;;) {
const { value, done } = await stream.next();
if (done || !value) break;
if (value.duration > 0) this.frameDt = value.duration;
- if (value.timestamp > at + 1e-4) break;
frames.push(value);
- if (frames.length > window) frames.shift();
- if (value.timestamp + value.duration > at + 1e-4) break;
+ if (frames.length > window + 1) frames.shift();
+ if (covered || value.timestamp > at + 1e-4) break;
+ if (value.timestamp + value.duration > at + 1e-4) covered = true;
}
} finally {
void stream.return(undefined).catch(() => {});
}
this.backFrames = frames;
- return frames.find(covering) ?? frames[frames.length - 1] ?? null;
+ return (
+ this.heldBack(at) ??
+ frames.filter((f) => f.timestamp <= at + 1e-4).pop() ??
+ frames[frames.length - 1] ??
+ null
+ );
+ }
+
+ /** The frame in the backward window covering `at`, if it holds one. */
+ private heldBack(at: number): WrappedCanvas | null {
+ return (
+ this.backFrames.find(
+ (f) => f.timestamp <= at + 1e-4 && at < f.timestamp + Math.max(f.duration, 1e-4) + 1e-4
+ ) ?? null
+ );
}
private dropBack(): void {
this.backFrames = [];
this.backSink = null;
+ this.pair = null;
}
dispose() {
@@ -1101,6 +1164,34 @@ export class FramePainter {
* holding a hundred decoders. Past the budget the least recently drawn are
* let go, which costs one reopen if the cut returns to them.
*/
+ /** The frame maker for smoothed slow motion, opened on the first frame
+ * that needs it. Its load — the runtime and the model — is part of the
+ * render, so a failure there fails the export like a decoder would. */
+ private synth: Promise<FrameSynth> | null = null;
+
+ /**
+ * A clip's picture at timeline time `t`: its source frame, or, on a clip
+ * smoothing its slow motion where the rate is under 1×, the frame made
+ * between the two source frames around that moment. At either edge of the
+ * pair the real frame shows.
+ */
+ private async frameOf(span: ClipSpan, t: number): Promise<Frame> {
+ const reader = this.readerFor(span.asset);
+ const st = sourceTimeAt(span, t);
+ if (!smoothsAt(span.clip, retimeOf(span.clip), Math.max(0, t - span.start))) return reader.frameAt(st);
+ const pair = await reader.pairAt(st);
+ if (!pair) return reader.frameAt(st);
+ if (!pair.b) return frameOfWrapped(pair.a);
+ const w = synthWeight(st, pair.a.timestamp, pair.b.timestamp);
+ if (w <= SYNTH_EDGE) return frameOfWrapped(pair.a);
+ if (w >= 1 - SYNTH_EDGE) return frameOfWrapped(pair.b);
+ const synth = await (this.synth ??= exportFrameSynth());
+ const { width, height } = pair.a.canvas;
+ const key = `${span.asset.id}|${pair.a.timestamp.toFixed(4)}|${pair.b.timestamp.toFixed(4)}`;
+ const image = await synth.mid(key, pair.a.canvas, pair.b.canvas, width, height, w);
+ return { kind: "ready", image, width, height };
+ }
+
private readerFor(asset: MediaAsset): ClipReader {
let r = this.readers.get(asset.id);
if (!r) this.readers.set(asset.id, (r = new ClipReader(asset, () => this.resolve(asset))));
@@ -1201,12 +1292,8 @@ export class FramePainter {
const frame = await this.readerFor(plan.backdrop.span.asset).frameAt(plan.backdrop.at);
comp.drawLayer(frame, plan.backdrop.span.clip, false, 1, t);
}
- const masterFrame = master.clip.hidden
- ? MISSING_FRAME
- : await this.readerFor(master.asset).frameAt(sourceTimeAt(master, t));
- const incFrame = plan.incoming
- ? await this.readerFor(plan.incoming.asset).frameAt(sourceTimeAt(plan.incoming, t))
- : MISSING_FRAME;
+ const masterFrame = master.clip.hidden ? MISSING_FRAME : await this.frameOf(master, t);
+ const incFrame = plan.incoming ? await this.frameOf(plan.incoming, t) : MISSING_FRAME;
comp.drawCrossJoin(
plan.style,
plan.p,
@@ -1234,7 +1321,7 @@ export class FramePainter {
const span = this.spanOfClip.get(layer.clip.id);
if (!span) continue;
await this.fetchRemovalMatte(span, t);
- const frame = await this.readerFor(layer.asset).frameAt(sourceTimeAt(span, t));
+ const frame = await this.frameOf(span, t);
comp.drawIntoRect(
frame,
rectOf(layer.clip),
@@ -1284,6 +1371,8 @@ export class FramePainter {
this.behind?.dispose();
for (const r of this.readers.values()) r.dispose();
this.readers.clear();
+ void this.synth?.then((s) => s.dispose()).catch(() => {});
+ this.synth = null;
this.releaseMemory();
}
}
diff --git a/site/src/cut/lib/frameSynth.ts b/site/src/cut/lib/frameSynth.ts
new file mode 100644
index 00000000..6d6a1bcd
--- /dev/null
+++ b/site/src/cut/lib/frameSynth.ts
@@ -0,0 +1,283 @@
+/**
+ * Smooth slow motion: the picture between two source frames.
+ *
+ * A clip slowed below 1× has fewer source frames than output frames, so the
+ * plain render shows each source frame several times and the motion steps.
+ * With smoothing on, the frames in between are made from the two source
+ * frames around them.
+ *
+ * Two makers. The preview blends the pair — a crossfade weighted by where
+ * the output frame falls between them — because it costs two draws and runs
+ * inside the frame budget. The export estimates the motion: RIFE, a frame
+ * interpolation network, run in the tab on WebGPU through ONNX Runtime, so
+ * a subject moves to where it would have been. A browser without WebGPU
+ * exports the blend, the one place the estimate cannot run; the ffmpeg
+ * exports (ProRes, headless, the engine's fallback) estimate motion with
+ * ffmpeg's own interpolation filter instead.
+ *
+ * The model and the runtime are staged under public/ at install
+ * (scripts/stage-frame-synth.mjs) and fetched on first use.
+ */
+
+import { createRasterCanvas, type RasterSurface } from "@/cut/lib/raster";
+
+/** Below this share of the way to the next frame the first frame shows as
+ * is, and above its mirror the next one does: a synthesized frame this close
+ * to a real one is the real one with noise. */
+export const SYNTH_EDGE = 0.02;
+
+/** Where an output frame at source second `t` falls between the source
+ * frames at `a` and `b`: 0 at `a`, 1 at `b`. */
+export function synthWeight(t: number, a: number, b: number): number {
+ const span = b - a;
+ if (!(span > 0)) return 0;
+ return Math.min(1, Math.max(0, (t - a) / span));
+}
+
+/** Draw `a` crossfaded toward `b` by `w` onto a canvas of `w × h` pixels. */
+export function blendInto(
+ canvas: RasterSurface,
+ a: CanvasImageSource,
+ b: CanvasImageSource,
+ w: number
+): void {
+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;
+ if (!ctx) return;
+ ctx.globalAlpha = 1;
+ ctx.drawImage(a, 0, 0, canvas.width, canvas.height);
+ ctx.globalAlpha = w;
+ ctx.drawImage(b, 0, 0, canvas.width, canvas.height);
+ ctx.globalAlpha = 1;
+}
+
+/** Canvases a maker hands out in turn before reusing one. A frame draws
+ * from up to two synthesized pictures at once — the two sides of a cross
+ * dissolve — so each has to survive the call after it. */
+export const SYNTH_OUTS = 3;
+
+/** A frame maker: the picture `w` of the way from `a` to `b`, drawn at
+ * `width × height`. The canvas returned is the maker's own; it stays as
+ * drawn through the next `SYNTH_OUTS − 1` calls and is redrawn after. `key`
+ * names the pair, so a maker that does heavy work per pair can keep it
+ * across the output frames between the same two sources. */
+export interface FrameSynth {
+ mid(
+ key: string,
+ a: CanvasImageSource,
+ b: CanvasImageSource,
+ width: number,
+ height: number,
+ w: number
+ ): Promise<RasterSurface>;
+ dispose(): void;
+}
+
+/** The blend as a maker, for the export on a machine without WebGPU. */
+export function blendSynth(): FrameSynth {
+ const outs = new OutRing();
+ return {
+ async mid(_key, a, b, width, height, w) {
+ const out = outs.next(width, height);
+ blendInto(out, a, b, w);
+ return out;
+ },
+ dispose() {
+ outs.clear();
+ },
+ };
+}
+
+/** The canvases a maker returns, handed out round-robin. */
+class OutRing {
+ private outs: RasterSurface[] = [];
+ private at = 0;
+ next(width: number, height: number): RasterSurface {
+ const i = this.at;
+ this.at = (i + 1) % SYNTH_OUTS;
+ let c = this.outs[i];
+ if (!c) c = this.outs[i] = createRasterCanvas(width, height);
+ if (c.width !== width) c.width = width;
+ if (c.height !== height) c.height = height;
+ return c;
+ }
+ clear(): void {
+ this.outs = [];
+ }
+}
+
+/** Keep in step with scripts/stage-frame-synth.mjs, which stages both. */
+const MODEL_URL = "/models/rife_v4.25.onnx";
+const RUNTIME_DIR = "/ort/";
+/** The model's convolutions stride the picture down five times. */
+const MULTIPLE = 32;
+/** Pixels the network runs over at most. A bigger frame is estimated at this
+ * size and the result drawn up to the frame's own: the slow stretch of a 4K
+ * clip is a touch softer, and the estimate stays a fraction of a second. */
+const AREA_CAP = 1920 * 1088;
+/** Planes of the model's one input: the two pictures, the timestep, and
+ * the sampling grid it warps with. */
+const PLANES = 11;
+
+type Ort = typeof import("onnxruntime-web/webgpu");
+
+/** Whether this browser can run the estimate. */
+export async function hasFrameSynthGpu(): Promise<boolean> {
+ const gpu = (
+ globalThis.navigator as Navigator & { gpu?: { requestAdapter(): Promise<unknown | null> } }
+ )?.gpu;
+ if (!gpu) return false;
+ try {
+ return (await gpu.requestAdapter()) !== null;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The motion-estimating maker. `create` loads the runtime and the model,
+ * and rejects when either cannot be had — that is the caller's error to
+ * surface, since a machine with WebGPU has no better maker to fall back on.
+ */
+export class RifeSynth implements FrameSynth {
+ private constructor(
+ private readonly ort: Ort,
+ private readonly session: import("onnxruntime-web/webgpu").InferenceSession
+ ) {}
+
+ static async create(): Promise<RifeSynth> {
+ const ort = await import("onnxruntime-web/webgpu");
+ ort.env.wasm.wasmPaths = RUNTIME_DIR;
+ const session = await ort.InferenceSession.create(MODEL_URL, {
+ executionProviders: ["webgpu"],
+ graphOptimizationLevel: "all",
+ });
+ return new RifeSynth(ort, session);
+ }
+
+ /** The network's picture size for the last pair, and the padded size it ran at. */
+ private inner = { w: 0, h: 0, W: 0, H: 0 };
+ /** The staged input: both pictures packed, grid planes filled, timestep
+ * rewritten per call. */
+ private input: Float32Array | null = null;
+ private pairKey = "";
+ /** Canvas the pictures are read through, at the padded size. */
+ private stage: RasterSurface | null = null;
+ /** The estimate at the padded size, and the frames handed back. */
+ private mid_: RasterSurface | null = null;
+ private pixels: ImageData | null = null;
+ private outs = new OutRing();
+
+ async mid(
+ key: string,
+ a: CanvasImageSource,
+ b: CanvasImageSource,
+ width: number,
+ height: number,
+ w: number
+ ): Promise<RasterSurface> {
+ const { w: iw, h: ih, W, H } = this.sizeFor(width, height);
+ if (this.pairKey !== key || !this.input) {
+ this.pack(a, b, iw, ih, W, H);
+ this.pairKey = key;
+ }
+ const input = this.input!;
+ input.fill(w, 6 * W * H, 7 * W * H);
+ const { ort, session } = this;
+ const tensor = new ort.Tensor("float32", input, [1, PLANES, H, W]);
+ const result = await session.run({ input: tensor });
+ const outT = result.output;
+ const data = outT.data as Float32Array;
+ if (!this.pixels || this.pixels.width !== W || this.pixels.height !== H)
+ this.pixels = new ImageData(W, H);
+ const rgba = this.pixels.data;
+ const plane = W * H;
+ for (let i = 0; i < plane; i++) {
+ const o = i * 4;
+ rgba[o] = data[i] * 255;
+ rgba[o + 1] = data[i + plane] * 255;
+ rgba[o + 2] = data[i + 2 * plane] * 255;
+ rgba[o + 3] = 255;
+ }
+ outT.dispose?.();
+ const mid = this.canvas("mid_", W, H);
+ (mid.getContext("2d") as CanvasRenderingContext2D).putImageData(this.pixels, 0, 0);
+ const out = this.outs.next(width, height);
+ const octx = out.getContext("2d") as CanvasRenderingContext2D;
+ octx.drawImage(mid, 0, 0, iw, ih, 0, 0, width, height);
+ return out;
+ }
+
+ /** The size the network sees a `width × height` frame at: scaled under the
+ * area cap, then padded up to the stride multiple. */
+ private sizeFor(width: number, height: number) {
+ const s = Math.min(1, Math.sqrt(AREA_CAP / Math.max(1, width * height)));
+ const iw = Math.max(1, Math.round(width * s));
+ const ih = Math.max(1, Math.round(height * s));
+ const W = Math.ceil(iw / MULTIPLE) * MULTIPLE;
+ const H = Math.ceil(ih / MULTIPLE) * MULTIPLE;
+ const same = this.inner.w === iw && this.inner.h === ih;
+ if (!same) {
+ this.inner = { w: iw, h: ih, W, H };
+ this.input = null;
+ this.pairKey = "";
+ this.pixels = null;
+ }
+ return this.inner;
+ }
+
+ private canvas(slot: "stage" | "mid_", w: number, h: number): RasterSurface {
+ let c = this[slot];
+ if (!c) c = this[slot] = createRasterCanvas(w, h);
+ if (c.width !== w) c.width = w;
+ if (c.height !== h) c.height = h;
+ return c;
+ }
+
+ /** Pack both pictures and the grid planes into the input. */
+ private pack(a: CanvasImageSource, b: CanvasImageSource, iw: number, ih: number, W: number, H: number) {
+ const plane = W * H;
+ const input = (this.input ??= new Float32Array(PLANES * plane));
+ const stage = this.canvas("stage", W, H);
+ const ctx = stage.getContext("2d", { willReadFrequently: true }) as CanvasRenderingContext2D;
+ const read = (img: CanvasImageSource, at: number) => {
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, W, H);
+ ctx.drawImage(img, 0, 0, iw, ih);
+ const d = ctx.getImageData(0, 0, W, H).data;
+ for (let i = 0; i < plane; i++) {
+ const o = i * 4;
+ input[at + i] = d[o] / 255;
+ input[at + plane + i] = d[o + 1] / 255;
+ input[at + 2 * plane + i] = d[o + 2] / 255;
+ }
+ };
+ read(a, 0);
+ read(b, 3 * plane);
+ // The sampling grid: normalized x and y of every pixel, and the size of
+ // one pixel in that space, which the flow scales by.
+ for (let y = 0; y < H; y++) {
+ const vy = (2 * y) / (H - 1) - 1;
+ for (let x = 0; x < W; x++) {
+ const i = y * W + x;
+ input[7 * plane + i] = (2 * x) / (W - 1) - 1;
+ input[8 * plane + i] = vy;
+ }
+ }
+ input.fill(2 / (W - 1), 9 * plane, 10 * plane);
+ input.fill(2 / (H - 1), 10 * plane, 11 * plane);
+ }
+
+ dispose(): void {
+ void this.session.release();
+ this.input = null;
+ this.stage = this.mid_ = null;
+ this.outs.clear();
+ this.pixels = null;
+ }
+}
+
+/** The maker an export uses: the estimate where the machine can run it,
+ * the blend where it cannot. */
+export async function exportFrameSynth(): Promise<FrameSynth> {
+ return (await hasFrameSynthGpu()) ? RifeSynth.create() : blendSynth();
+}