OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: add smooth slow motion with optical flow frame interpolation
Augustus Otu3d01ecc05975
diff --git a/apps/web/src/components/editor/inspector/SpeedSection.tsx b/apps/web/src/components/editor/inspector/SpeedSection.tsxindex 7c3e32d0..6aa84269 100644--- a/apps/web/src/components/editor/inspector/SpeedSection.tsx+++ b/apps/web/src/components/editor/inspector/SpeedSection.tsx@@ -1,9 +1,9 @@import React, { useState, useEffect } from "react";-import { RotateCcw } from "lucide-react";+import { RotateCcw, Sparkles } from "lucide-react";import type { Clip } from "@openreel/core";import { getSpeedEngine } from "@openreel/core";import { useProjectStore } from "../../../stores/project-store";-import { Input, Switch, Label } from "@openreel/ui";+import { Input, Switch, Label, Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@openreel/ui";interface SpeedSectionProps {clip: Clip;@@ -227,6 +227,77 @@ export const SpeedSection: React.FC<SpeedSectionProps> = ({ clip }) => {{isReversed ? "Reversed" : "Reverse Clip"}</button>+ {currentSpeed < 1 && (+ <div className="space-y-2 p-3 rounded-lg bg-background-tertiary border border-border">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Sparkles size={14} className="text-primary" />+ <Label htmlFor="smooth-slowmo" className="text-xs text-text-secondary">+ Smooth Slow Motion+ </Label>+ </div>+ <Switch+ id="smooth-slowmo"+ checked={clip.smoothSlowMo ?? false}+ onCheckedChange={(checked) => {+ const tracks = project.timeline.tracks.map((track) => {+ const clipIndex = track.clips.findIndex((c) => c.id === clip.id);+ if (clipIndex === -1) return track;+ const updatedClip = { ...track.clips[clipIndex], smoothSlowMo: checked };+ const newClips = [...track.clips];+ newClips[clipIndex] = updatedClip;+ return { ...track, clips: newClips };+ });+ useProjectStore.setState({+ project: {+ ...project,+ timeline: { ...project.timeline, tracks },+ modifiedAt: Date.now(),+ },+ });+ }}+ />+ </div>+ {clip.smoothSlowMo && (+ <div className="space-y-1">+ <Label className="text-xs text-text-tertiary">Quality</Label>+ <Select+ value={clip.interpolationQuality ?? "medium"}+ onValueChange={(value: "low" | "medium" | "high") => {+ const tracks = project.timeline.tracks.map((track) => {+ const clipIndex = track.clips.findIndex((c) => c.id === clip.id);+ if (clipIndex === -1) return track;+ const updatedClip = { ...track.clips[clipIndex], interpolationQuality: value };+ const newClips = [...track.clips];+ newClips[clipIndex] = updatedClip;+ return { ...track, clips: newClips };+ });+ useProjectStore.setState({+ project: {+ ...project,+ timeline: { ...project.timeline, tracks },+ modifiedAt: Date.now(),+ },+ });+ }}+ >+ <SelectTrigger className="h-8 text-xs bg-background-elevated border-border">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="low">Low (faster)</SelectItem>+ <SelectItem value="medium">Medium</SelectItem>+ <SelectItem value="high">High (slower)</SelectItem>+ </SelectContent>+ </Select>+ <p className="text-[10px] text-text-tertiary">+ Uses optical flow to generate smooth in-between frames+ </p>+ </div>+ )}+ </div>+ )}+{(currentSpeed !== 1 || isReversed) && (<div className="p-3 rounded-lg bg-background-tertiary border border-border"><div className="text-xs text-text-tertiary mb-1">@@ -234,6 +305,7 @@ export const SpeedSection: React.FC<SpeedSectionProps> = ({ clip }) => {</div><div className="text-sm text-text-primary">Speed: {currentSpeed}× {isReversed && "• Reversed"}+ {clip.smoothSlowMo && " • Smooth"}</div></div>)}diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.tsindex 9c7de320..3d4ccb1b 100644--- a/packages/core/src/types/timeline.ts+++ b/packages/core/src/types/timeline.ts@@ -58,6 +58,8 @@ export interface Clip {readonly keyframes: Keyframe[];readonly speed?: number;readonly reversed?: boolean;+ readonly smoothSlowMo?: boolean;+ readonly interpolationQuality?: "low" | "medium" | "high";readonly emphasisAnimation?: EmphasisAnimation;/** Zero-based index of the audio track within the source media file to use for this clip.* Undefined or 0 means the primary/first audio track. */diff --git a/packages/core/src/video/frame-interpolation/flow-field-cache.ts b/packages/core/src/video/frame-interpolation/flow-field-cache.tsnew file mode 100644index 00000000..6553c9e7--- /dev/null+++ b/packages/core/src/video/frame-interpolation/flow-field-cache.ts@@ -0,0 +1,53 @@+import type { FlowField } from "./types";++interface CacheEntry {+ flowField: FlowField;+ lastAccessed: number;+}++export class FlowFieldCache {+ private cache: Map<string, CacheEntry> = new Map();+ private maxEntries: number;++ constructor(maxEntries: number = 10) {+ this.maxEntries = maxEntries;+ }++ static makeKey(mediaId: string, timeBefore: number, timeAfter: number): string {+ return `${mediaId}:${timeBefore.toFixed(4)}:${timeAfter.toFixed(4)}`;+ }++ get(key: string): FlowField | null {+ const entry = this.cache.get(key);+ if (!entry) return null;+ entry.lastAccessed = performance.now();+ return entry.flowField;+ }++ set(key: string, flowField: FlowField): void {+ if (this.cache.size >= this.maxEntries) {+ this.evictLRU();+ }+ this.cache.set(key, { flowField, lastAccessed: performance.now() });+ }++ private evictLRU(): void {+ let oldestKey = "";+ let oldestTime = Infinity;++ for (const [key, entry] of this.cache) {+ if (entry.lastAccessed < oldestTime) {+ oldestTime = entry.lastAccessed;+ oldestKey = key;+ }+ }++ if (oldestKey) {+ this.cache.delete(oldestKey);+ }+ }++ clear(): void {+ this.cache.clear();+ }+}diff --git a/packages/core/src/video/frame-interpolation/frame-interpolation-engine.ts b/packages/core/src/video/frame-interpolation/frame-interpolation-engine.tsnew file mode 100644index 00000000..850b1ea0--- /dev/null+++ b/packages/core/src/video/frame-interpolation/frame-interpolation-engine.ts@@ -0,0 +1,224 @@+import type { FlowField, InterpolationConfig, FrameInterpolationResult } from "./types";+import { INTERPOLATION_QUALITY_PRESETS } from "./types";+import { OpticalFlowGPU } from "./optical-flow-gpu";+import { OpticalFlowCPU } from "./optical-flow-cpu";+import { FlowFieldCache } from "./flow-field-cache";++export class FrameInterpolationEngine {+ private gpuFlow: OpticalFlowGPU | null = null;+ private cpuFlow: OpticalFlowCPU;+ private cache: FlowFieldCache;+ private config: InterpolationConfig;+ private gpuReady: boolean = false;+ private initPromise: Promise<void> | null = null;+ private budgetExceeded: boolean = false;+ private frameBudgetMs: number = 16;++ constructor(quality: "low" | "medium" | "high" = "medium") {+ this.config = INTERPOLATION_QUALITY_PRESETS[quality];+ this.cpuFlow = new OpticalFlowCPU(this.config);+ this.cache = new FlowFieldCache(10);+ }++ async initialize(): Promise<void> {+ if (this.initPromise) return this.initPromise;++ this.initPromise = (async () => {+ this.gpuFlow = new OpticalFlowGPU(this.config);+ this.gpuReady = await this.gpuFlow.initialize();+ if (!this.gpuReady) {+ this.gpuFlow = null;+ }+ })();++ return this.initPromise;+ }++ setQuality(quality: "low" | "medium" | "high"): void {+ this.config = INTERPOLATION_QUALITY_PRESETS[quality];+ this.cpuFlow = new OpticalFlowCPU(this.config);+ if (this.gpuFlow) {+ this.gpuFlow.dispose();+ this.gpuFlow = new OpticalFlowGPU(this.config);+ this.gpuFlow.initialize().then((ready) => {+ this.gpuReady = ready;+ if (!ready) this.gpuFlow = null;+ });+ }+ this.cache.clear();+ }++ setFrameBudget(ms: number): void {+ this.frameBudgetMs = ms;+ }++ resetBudget(): void {+ this.budgetExceeded = false;+ }++ async interpolate(+ frame1: ImageBitmap,+ frame2: ImageBitmap,+ t: number,+ mediaId: string,+ timeBefore: number,+ timeAfter: number,+ ): Promise<FrameInterpolationResult> {+ const startTime = performance.now();++ if (this.budgetExceeded) {+ return this.simpleBlend(frame1, frame2, t, startTime);+ }++ try {+ const cacheKey = FlowFieldCache.makeKey(mediaId, timeBefore, timeAfter);+ let flowField = this.cache.get(cacheKey);++ const width = frame1.width;+ const height = frame1.height;++ if (!flowField) {+ const { data1, data2 } = this.extractPixelData(frame1, frame2);++ if (this.gpuReady && this.gpuFlow) {+ const pixels1 = new Uint32Array(data1.buffer);+ const pixels2 = new Uint32Array(data2.buffer);+ flowField = await this.gpuFlow.computeFlowField(+ pixels1,+ pixels2,+ width,+ height,+ );+ } else {+ const imgData1 = new ImageData(data1.slice(0) as unknown as Uint8ClampedArray<ArrayBuffer>, width, height);+ const imgData2 = new ImageData(data2.slice(0) as unknown as Uint8ClampedArray<ArrayBuffer>, width, height);+ flowField = await this.cpuFlow.computeFlowField(imgData1, imgData2);+ }++ this.cache.set(cacheKey, flowField);+ }++ const result = await this.warpFrames(+ frame1,+ frame2,+ flowField,+ width,+ height,+ t,+ );++ const computeTimeMs = performance.now() - startTime;++ if (computeTimeMs > this.frameBudgetMs * 2) {+ this.budgetExceeded = true;+ }++ return { frame: result, computeTimeMs, method: "optical-flow" };+ } catch {+ return this.simpleBlend(frame1, frame2, t, startTime);+ }+ }++ private extractPixelData(+ frame1: ImageBitmap,+ frame2: ImageBitmap,+ ): { data1: Uint8ClampedArray; data2: Uint8ClampedArray } {+ const canvas = new OffscreenCanvas(frame1.width, frame1.height);+ const ctx = canvas.getContext("2d")!;++ ctx.drawImage(frame1, 0, 0);+ const data1 = ctx.getImageData(0, 0, frame1.width, frame1.height).data;++ ctx.drawImage(frame2, 0, 0);+ const data2 = ctx.getImageData(0, 0, frame2.width, frame2.height).data;++ return { data1, data2 };+ }++ private async warpFrames(+ frame1: ImageBitmap,+ frame2: ImageBitmap,+ flowField: FlowField,+ width: number,+ height: number,+ t: number,+ ): Promise<ImageBitmap> {+ if (this.gpuReady && this.gpuFlow) {+ const { data1, data2 } = this.extractPixelData(frame1, frame2);+ const pixels1 = new Uint32Array(data1.buffer);+ const pixels2 = new Uint32Array(data2.buffer);++ const resultPixels = await this.gpuFlow.warpAndBlend(+ pixels1,+ pixels2,+ flowField,+ width,+ height,+ t,+ );++ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext("2d")!;+ const imageData = ctx.createImageData(width, height);+ new Uint32Array(imageData.data.buffer).set(resultPixels);+ ctx.putImageData(imageData, 0, 0);+ return canvas.transferToImageBitmap();+ }++ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext("2d")!;++ ctx.drawImage(frame1, 0, 0);+ const imgData1 = ctx.getImageData(0, 0, width, height);+ ctx.drawImage(frame2, 0, 0);+ const imgData2 = ctx.getImageData(0, 0, width, height);++ const result = this.cpuFlow.warpAndBlend(imgData1, imgData2, flowField, t);+ ctx.putImageData(result, 0, 0);+ return canvas.transferToImageBitmap();+ }++ private async simpleBlend(+ frame1: ImageBitmap,+ frame2: ImageBitmap,+ t: number,+ startTime: number,+ ): Promise<FrameInterpolationResult> {+ const canvas = new OffscreenCanvas(frame1.width, frame1.height);+ const ctx = canvas.getContext("2d")!;++ ctx.globalAlpha = 1 - t;+ ctx.drawImage(frame1, 0, 0);+ ctx.globalAlpha = t;+ ctx.drawImage(frame2, 0, 0);+ ctx.globalAlpha = 1;++ const frame = canvas.transferToImageBitmap();+ return {+ frame,+ computeTimeMs: performance.now() - startTime,+ method: "blend",+ };+ }++ dispose(): void {+ this.gpuFlow?.dispose();+ this.gpuFlow = null;+ this.cache.clear();+ }+}++let interpolationEngineInstance: FrameInterpolationEngine | null = null;++export function getFrameInterpolationEngine(): FrameInterpolationEngine {+ if (!interpolationEngineInstance) {+ interpolationEngineInstance = new FrameInterpolationEngine();+ interpolationEngineInstance.initialize();+ }+ return interpolationEngineInstance;+}++export function disposeFrameInterpolationEngine(): void {+ interpolationEngineInstance?.dispose();+ interpolationEngineInstance = null;+}diff --git a/packages/core/src/video/frame-interpolation/index.ts b/packages/core/src/video/frame-interpolation/index.tsnew file mode 100644index 00000000..405480cb--- /dev/null+++ b/packages/core/src/video/frame-interpolation/index.ts@@ -0,0 +1,6 @@+export { FrameInterpolationEngine, getFrameInterpolationEngine, disposeFrameInterpolationEngine } from "./frame-interpolation-engine";+export { OpticalFlowGPU } from "./optical-flow-gpu";+export { OpticalFlowCPU } from "./optical-flow-cpu";+export { FlowFieldCache } from "./flow-field-cache";+export type { FlowField, InterpolationConfig, FrameInterpolationResult } from "./types";+export { INTERPOLATION_QUALITY_PRESETS } from "./types";diff --git a/packages/core/src/video/frame-interpolation/optical-flow-cpu.ts b/packages/core/src/video/frame-interpolation/optical-flow-cpu.tsnew file mode 100644index 00000000..57098078--- /dev/null+++ b/packages/core/src/video/frame-interpolation/optical-flow-cpu.ts@@ -0,0 +1,319 @@+import type { FlowField, InterpolationConfig } from "./types";++export class OpticalFlowCPU {+ private config: InterpolationConfig;++ constructor(config: InterpolationConfig) {+ this.config = config;+ }++ async computeFlowField(+ frame1: ImageData,+ frame2: ImageData,+ ): Promise<FlowField> {+ const { blockSize, searchRadius, pyramidLevels } = this.config;++ const pyramid1 = this.buildPyramid(frame1, pyramidLevels);+ const pyramid2 = this.buildPyramid(frame2, pyramidLevels);++ const coarsestWidth = pyramid1[pyramidLevels - 1].width;+ const coarsestHeight = pyramid1[pyramidLevels - 1].height;+ const blocksX = Math.ceil(coarsestWidth / blockSize);+ const blocksY = Math.ceil(coarsestHeight / blockSize);++ let flowField: FlowField = {+ width: blocksX,+ height: blocksY,+ vectors: new Float32Array(blocksX * blocksY * 2),+ };++ for (let level = pyramidLevels - 1; level >= 0; level--) {+ const img1 = pyramid1[level];+ const img2 = pyramid2[level];+ const levelBlocksX = Math.ceil(img1.width / blockSize);+ const levelBlocksY = Math.ceil(img1.height / blockSize);+ const levelFlow: FlowField = {+ width: levelBlocksX,+ height: levelBlocksY,+ vectors: new Float32Array(levelBlocksX * levelBlocksY * 2),+ };++ const scale = level < pyramidLevels - 1 ? 2 : 1;+ const effectiveSearchRadius = Math.ceil(searchRadius / (level + 1));++ for (let by = 0; by < levelBlocksY; by++) {+ for (let bx = 0; bx < levelBlocksX; bx++) {+ let initialDx = 0;+ let initialDy = 0;++ if (level < pyramidLevels - 1) {+ const prevBx = Math.min(+ Math.floor(bx / scale),+ flowField.width - 1,+ );+ const prevBy = Math.min(+ Math.floor(by / scale),+ flowField.height - 1,+ );+ const prevIdx = (prevBy * flowField.width + prevBx) * 2;+ initialDx = flowField.vectors[prevIdx] * scale;+ initialDy = flowField.vectors[prevIdx + 1] * scale;+ }++ const { dx, dy } = this.blockMatch(+ img1,+ img2,+ bx * blockSize,+ by * blockSize,+ blockSize,+ effectiveSearchRadius,+ initialDx,+ initialDy,+ );++ const idx = (by * levelBlocksX + bx) * 2;+ levelFlow.vectors[idx] = dx;+ levelFlow.vectors[idx + 1] = dy;+ }+ }++ flowField = levelFlow;+ }++ return flowField;+ }++ warpAndBlend(+ frame1: ImageData,+ frame2: ImageData,+ flowField: FlowField,+ t: number,+ ): ImageData {+ const width = frame1.width;+ const height = frame1.height;+ const output = new ImageData(width, height);+ const { blockSize } = this.config;++ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const bx = Math.min(+ Math.floor(x / blockSize),+ flowField.width - 1,+ );+ const by = Math.min(+ Math.floor(y / blockSize),+ flowField.height - 1,+ );+ const flowIdx = (by * flowField.width + bx) * 2;+ const dx = flowField.vectors[flowIdx];+ const dy = flowField.vectors[flowIdx + 1];++ const src1X = x - dx * t;+ const src1Y = y - dy * t;+ const src2X = x + dx * (1 - t);+ const src2Y = y + dy * (1 - t);++ const pixel1 = this.bilinearSample(frame1, src1X, src1Y);+ const pixel2 = this.bilinearSample(frame2, src2X, src2Y);++ const outIdx = (y * width + x) * 4;+ output.data[outIdx] = pixel1[0] * (1 - t) + pixel2[0] * t;+ output.data[outIdx + 1] = pixel1[1] * (1 - t) + pixel2[1] * t;+ output.data[outIdx + 2] = pixel1[2] * (1 - t) + pixel2[2] * t;+ output.data[outIdx + 3] = 255;+ }+ }++ return output;+ }++ private blockMatch(+ img1: ImageData,+ img2: ImageData,+ blockX: number,+ blockY: number,+ blockSize: number,+ searchRadius: number,+ initialDx: number,+ initialDy: number,+ ): { dx: number; dy: number } {+ let bestDx = initialDx;+ let bestDy = initialDy;+ let bestSAD = Infinity;++ const centerSearchX = Math.round(initialDx);+ const centerSearchY = Math.round(initialDy);++ for (let sy = -searchRadius; sy <= searchRadius; sy += 2) {+ for (let sx = -searchRadius; sx <= searchRadius; sx += 2) {+ const dx = centerSearchX + sx;+ const dy = centerSearchY + sy;+ const sad = this.computeSAD(+ img1,+ img2,+ blockX,+ blockY,+ blockX + dx,+ blockY + dy,+ blockSize,+ );++ if (sad < bestSAD) {+ bestSAD = sad;+ bestDx = dx;+ bestDy = dy;+ }+ }+ }++ for (let sy = -1; sy <= 1; sy++) {+ for (let sx = -1; sx <= 1; sx++) {+ if (sx === 0 && sy === 0) continue;+ const dx = bestDx + sx;+ const dy = bestDy + sy;+ const sad = this.computeSAD(+ img1,+ img2,+ blockX,+ blockY,+ blockX + dx,+ blockY + dy,+ blockSize,+ );++ if (sad < bestSAD) {+ bestSAD = sad;+ bestDx = dx;+ bestDy = dy;+ }+ }+ }++ return { dx: bestDx, dy: bestDy };+ }++ private computeSAD(+ img1: ImageData,+ img2: ImageData,+ x1: number,+ y1: number,+ x2: number,+ y2: number,+ blockSize: number,+ ): number {+ let sad = 0;+ const w = img1.width;+ const h = img1.height;++ for (let dy = 0; dy < blockSize; dy++) {+ for (let dx = 0; dx < blockSize; dx++) {+ const px1 = x1 + dx;+ const py1 = y1 + dy;+ const px2 = x2 + dx;+ const py2 = y2 + dy;++ if (px1 < 0 || px1 >= w || py1 < 0 || py1 >= h) {+ sad += 128;+ continue;+ }+ if (px2 < 0 || px2 >= w || py2 < 0 || py2 >= h) {+ sad += 128;+ continue;+ }++ const idx1 = (py1 * w + px1) * 4;+ const idx2 = (py2 * w + px2) * 4;++ const gray1 =+ img1.data[idx1] * 0.299 ++ img1.data[idx1 + 1] * 0.587 ++ img1.data[idx1 + 2] * 0.114;+ const gray2 =+ img2.data[idx2] * 0.299 ++ img2.data[idx2 + 1] * 0.587 ++ img2.data[idx2 + 2] * 0.114;++ sad += Math.abs(gray1 - gray2);+ }+ }++ return sad;+ }++ private bilinearSample(+ img: ImageData,+ x: number,+ y: number,+ ): [number, number, number] {+ const w = img.width;+ const h = img.height;+ const x0 = Math.max(0, Math.min(w - 1, Math.floor(x)));+ const y0 = Math.max(0, Math.min(h - 1, Math.floor(y)));+ const x1 = Math.min(w - 1, x0 + 1);+ const y1 = Math.min(h - 1, y0 + 1);+ const fx = x - x0;+ const fy = y - y0;++ const idx00 = (y0 * w + x0) * 4;+ const idx10 = (y0 * w + x1) * 4;+ const idx01 = (y1 * w + x0) * 4;+ const idx11 = (y1 * w + x1) * 4;++ const r =+ img.data[idx00] * (1 - fx) * (1 - fy) ++ img.data[idx10] * fx * (1 - fy) ++ img.data[idx01] * (1 - fx) * fy ++ img.data[idx11] * fx * fy;+ const g =+ img.data[idx00 + 1] * (1 - fx) * (1 - fy) ++ img.data[idx10 + 1] * fx * (1 - fy) ++ img.data[idx01 + 1] * (1 - fx) * fy ++ img.data[idx11 + 1] * fx * fy;+ const b =+ img.data[idx00 + 2] * (1 - fx) * (1 - fy) ++ img.data[idx10 + 2] * fx * (1 - fy) ++ img.data[idx01 + 2] * (1 - fx) * fy ++ img.data[idx11 + 2] * fx * fy;++ return [r, g, b];+ }++ private buildPyramid(img: ImageData, levels: number): ImageData[] {+ const pyramid: ImageData[] = [img];++ for (let i = 1; i < levels; i++) {+ const prev = pyramid[i - 1];+ const newW = Math.max(1, Math.floor(prev.width / 2));+ const newH = Math.max(1, Math.floor(prev.height / 2));+ const downsampled = new ImageData(newW, newH);++ for (let y = 0; y < newH; y++) {+ for (let x = 0; x < newW; x++) {+ const srcX = x * 2;+ const srcY = y * 2;+ const idx = (y * newW + x) * 4;++ const s00 = (srcY * prev.width + srcX) * 4;+ const s10 = (srcY * prev.width + Math.min(srcX + 1, prev.width - 1)) * 4;+ const s01 = (Math.min(srcY + 1, prev.height - 1) * prev.width + srcX) * 4;+ const s11 =+ (Math.min(srcY + 1, prev.height - 1) * prev.width ++ Math.min(srcX + 1, prev.width - 1)) *+ 4;++ downsampled.data[idx] =+ (prev.data[s00] + prev.data[s10] + prev.data[s01] + prev.data[s11]) >> 2;+ downsampled.data[idx + 1] =+ (prev.data[s00 + 1] + prev.data[s10 + 1] + prev.data[s01 + 1] + prev.data[s11 + 1]) >> 2;+ downsampled.data[idx + 2] =+ (prev.data[s00 + 2] + prev.data[s10 + 2] + prev.data[s01 + 2] + prev.data[s11 + 2]) >> 2;+ downsampled.data[idx + 3] = 255;+ }+ }++ pyramid.push(downsampled);+ }++ return pyramid;+ }+}diff --git a/packages/core/src/video/frame-interpolation/optical-flow-gpu.ts b/packages/core/src/video/frame-interpolation/optical-flow-gpu.tsnew file mode 100644index 00000000..9d6245da--- /dev/null+++ b/packages/core/src/video/frame-interpolation/optical-flow-gpu.ts@@ -0,0 +1,377 @@+import type { FlowField, InterpolationConfig } from "./types";++const BLOCK_MATCH_SHADER = /* wgsl */ `+struct Params {+ width: u32,+ height: u32,+ blockSize: u32,+ searchRadius: u32,+ blocksX: u32,+ blocksY: u32,+}++@group(0) @binding(0) var<uniform> params: Params;+@group(0) @binding(1) var<storage, read> frame1: array<u32>;+@group(0) @binding(2) var<storage, read> frame2: array<u32>;+@group(0) @binding(3) var<storage, read_write> flowOutput: array<f32>;++fn getGray(frame: ptr<storage, array<u32>, read>, x: u32, y: u32) -> f32 {+ if (x >= params.width || y >= params.height) { return 0.0; }+ let pixel = (*frame)[y * params.width + x];+ let r = f32((pixel >> 0u) & 0xFFu);+ let g = f32((pixel >> 8u) & 0xFFu);+ let b = f32((pixel >> 16u) & 0xFFu);+ return r * 0.299 + g * 0.587 + b * 0.114;+}++fn computeSAD(bx: u32, by: u32, dx: i32, dy: i32) -> f32 {+ var sad: f32 = 0.0;+ for (var iy: u32 = 0u; iy < params.blockSize; iy++) {+ for (var ix: u32 = 0u; ix < params.blockSize; ix++) {+ let x1 = bx * params.blockSize + ix;+ let y1 = by * params.blockSize + iy;+ let x2 = i32(x1) + dx;+ let y2 = i32(y1) + dy;++ if (x2 < 0 || x2 >= i32(params.width) || y2 < 0 || y2 >= i32(params.height)) {+ sad += 128.0;+ continue;+ }++ let g1 = getGray(&frame1, x1, y1);+ let g2 = getGray(&frame2, u32(x2), u32(y2));+ sad += abs(g1 - g2);+ }+ }+ return sad;+}++@compute @workgroup_size(8, 8)+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {+ let bx = gid.x;+ let by = gid.y;+ if (bx >= params.blocksX || by >= params.blocksY) { return; }++ var bestDx: i32 = 0;+ var bestDy: i32 = 0;+ var bestSAD: f32 = 1e20;+ let sr = i32(params.searchRadius);++ for (var sy: i32 = -sr; sy <= sr; sy += 2) {+ for (var sx: i32 = -sr; sx <= sr; sx += 2) {+ let sad = computeSAD(bx, by, sx, sy);+ if (sad < bestSAD) {+ bestSAD = sad;+ bestDx = sx;+ bestDy = sy;+ }+ }+ }++ for (var sy: i32 = -1; sy <= 1; sy++) {+ for (var sx: i32 = -1; sx <= 1; sx++) {+ if (sx == 0 && sy == 0) { continue; }+ let sad = computeSAD(bx, by, bestDx + sx, bestDy + sy);+ if (sad < bestSAD) {+ bestSAD = sad;+ bestDx = bestDx + sx;+ bestDy = bestDy + sy;+ }+ }+ }++ let idx = (by * params.blocksX + bx) * 2u;+ flowOutput[idx] = f32(bestDx);+ flowOutput[idx + 1u] = f32(bestDy);+}+`;++const WARP_BLEND_SHADER = /* wgsl */ `+struct WarpParams {+ width: u32,+ height: u32,+ blocksX: u32,+ blocksY: u32,+ blockSize: u32,+ t: f32,+}++@group(0) @binding(0) var<uniform> params: WarpParams;+@group(0) @binding(1) var<storage, read> frame1: array<u32>;+@group(0) @binding(2) var<storage, read> frame2: array<u32>;+@group(0) @binding(3) var<storage, read> flow: array<f32>;+@group(0) @binding(4) var<storage, read_write> output: array<u32>;++fn sampleFrame(frame: ptr<storage, array<u32>, read>, fx: f32, fy: f32) -> vec4<f32> {+ let x0 = u32(clamp(floor(fx), 0.0, f32(params.width - 1u)));+ let y0 = u32(clamp(floor(fy), 0.0, f32(params.height - 1u)));+ let x1 = min(x0 + 1u, params.width - 1u);+ let y1 = min(y0 + 1u, params.height - 1u);+ let wx = fx - floor(fx);+ let wy = fy - floor(fy);++ let p00 = (*frame)[y0 * params.width + x0];+ let p10 = (*frame)[y0 * params.width + x1];+ let p01 = (*frame)[y1 * params.width + x0];+ let p11 = (*frame)[y1 * params.width + x1];++ let c00 = vec4<f32>(f32(p00 & 0xFFu), f32((p00 >> 8u) & 0xFFu), f32((p00 >> 16u) & 0xFFu), 255.0);+ let c10 = vec4<f32>(f32(p10 & 0xFFu), f32((p10 >> 8u) & 0xFFu), f32((p10 >> 16u) & 0xFFu), 255.0);+ let c01 = vec4<f32>(f32(p01 & 0xFFu), f32((p01 >> 8u) & 0xFFu), f32((p01 >> 16u) & 0xFFu), 255.0);+ let c11 = vec4<f32>(f32(p11 & 0xFFu), f32((p11 >> 8u) & 0xFFu), f32((p11 >> 16u) & 0xFFu), 255.0);++ return mix(mix(c00, c10, wx), mix(c01, c11, wx), wy);+}++@compute @workgroup_size(16, 16)+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {+ let x = gid.x;+ let y = gid.y;+ if (x >= params.width || y >= params.height) { return; }++ let bx = min(x / params.blockSize, params.blocksX - 1u);+ let by = min(y / params.blockSize, params.blocksY - 1u);+ let flowIdx = (by * params.blocksX + bx) * 2u;+ let dx = flow[flowIdx];+ let dy = flow[flowIdx + 1u];++ let src1X = f32(x) - dx * params.t;+ let src1Y = f32(y) - dy * params.t;+ let src2X = f32(x) + dx * (1.0 - params.t);+ let src2Y = f32(y) + dy * (1.0 - params.t);++ let color1 = sampleFrame(&frame1, src1X, src1Y);+ let color2 = sampleFrame(&frame2, src2X, src2Y);+ let blended = mix(color1, color2, params.t);++ let r = u32(clamp(blended.x, 0.0, 255.0));+ let g = u32(clamp(blended.y, 0.0, 255.0));+ let b = u32(clamp(blended.z, 0.0, 255.0));+ output[y * params.width + x] = r | (g << 8u) | (b << 16u) | (255u << 24u);+}+`;++export class OpticalFlowGPU {+ private device: GPUDevice | null = null;+ private blockMatchPipeline: GPUComputePipeline | null = null;+ private warpBlendPipeline: GPUComputePipeline | null = null;+ private config: InterpolationConfig;++ constructor(config: InterpolationConfig) {+ this.config = config;+ }++ async initialize(): Promise<boolean> {+ if (!navigator.gpu) return false;++ try {+ const adapter = await navigator.gpu.requestAdapter();+ if (!adapter) return false;++ this.device = await adapter.requestDevice();++ const blockMatchModule = this.device.createShaderModule({+ code: BLOCK_MATCH_SHADER,+ });+ this.blockMatchPipeline = this.device.createComputePipeline({+ layout: "auto",+ compute: { module: blockMatchModule, entryPoint: "main" },+ });++ const warpModule = this.device.createShaderModule({+ code: WARP_BLEND_SHADER,+ });+ this.warpBlendPipeline = this.device.createComputePipeline({+ layout: "auto",+ compute: { module: warpModule, entryPoint: "main" },+ });++ return true;+ } catch {+ return false;+ }+ }++ isReady(): boolean {+ return this.device !== null && this.blockMatchPipeline !== null;+ }++ async computeFlowField(+ frame1Data: Uint32Array,+ frame2Data: Uint32Array,+ width: number,+ height: number,+ ): Promise<FlowField> {+ if (!this.device || !this.blockMatchPipeline) {+ throw new Error("GPU not initialized");+ }++ const { blockSize, searchRadius } = this.config;+ const blocksX = Math.ceil(width / blockSize);+ const blocksY = Math.ceil(height / blockSize);++ const paramsBuffer = this.device.createBuffer({+ size: 24,+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(+ paramsBuffer,+ 0,+ new Uint32Array([width, height, blockSize, searchRadius, blocksX, blocksY]),+ );++ const frame1Buffer = this.device.createBuffer({+ size: frame1Data.byteLength,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(frame1Buffer, 0, frame1Data as unknown as Uint32Array<ArrayBuffer>);++ const frame2Buffer = this.device.createBuffer({+ size: frame2Data.byteLength,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(frame2Buffer, 0, frame2Data as unknown as Uint32Array<ArrayBuffer>);++ const flowSize = blocksX * blocksY * 2 * 4;+ const flowBuffer = this.device.createBuffer({+ size: flowSize,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,+ });++ const bindGroup = this.device.createBindGroup({+ layout: this.blockMatchPipeline.getBindGroupLayout(0),+ entries: [+ { binding: 0, resource: { buffer: paramsBuffer } },+ { binding: 1, resource: { buffer: frame1Buffer } },+ { binding: 2, resource: { buffer: frame2Buffer } },+ { binding: 3, resource: { buffer: flowBuffer } },+ ],+ });++ const encoder = this.device.createCommandEncoder();+ const pass = encoder.beginComputePass();+ pass.setPipeline(this.blockMatchPipeline);+ pass.setBindGroup(0, bindGroup);+ pass.dispatchWorkgroups(Math.ceil(blocksX / 8), Math.ceil(blocksY / 8));+ pass.end();++ const readBuffer = this.device.createBuffer({+ size: flowSize,+ usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,+ });+ encoder.copyBufferToBuffer(flowBuffer, 0, readBuffer, 0, flowSize);++ this.device.queue.submit([encoder.finish()]);++ await readBuffer.mapAsync(GPUMapMode.READ);+ const flowData = new Float32Array(readBuffer.getMappedRange().slice(0));+ readBuffer.unmap();++ paramsBuffer.destroy();+ frame1Buffer.destroy();+ frame2Buffer.destroy();+ flowBuffer.destroy();+ readBuffer.destroy();++ return { width: blocksX, height: blocksY, vectors: flowData };+ }++ async warpAndBlend(+ frame1Data: Uint32Array,+ frame2Data: Uint32Array,+ flowField: FlowField,+ width: number,+ height: number,+ t: number,+ ): Promise<Uint32Array> {+ if (!this.device || !this.warpBlendPipeline) {+ throw new Error("GPU not initialized");+ }++ const { blockSize } = this.config;+ const paramsData = new ArrayBuffer(24);+ const paramsView = new DataView(paramsData);+ paramsView.setUint32(0, width, true);+ paramsView.setUint32(4, height, true);+ paramsView.setUint32(8, flowField.width, true);+ paramsView.setUint32(12, flowField.height, true);+ paramsView.setUint32(16, blockSize, true);+ paramsView.setFloat32(20, t, true);++ const paramsBuffer = this.device.createBuffer({+ size: 24,+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(paramsBuffer, 0, new Uint8Array(paramsData));++ const frame1Buffer = this.device.createBuffer({+ size: frame1Data.byteLength,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(frame1Buffer, 0, frame1Data as unknown as Uint32Array<ArrayBuffer>);++ const frame2Buffer = this.device.createBuffer({+ size: frame2Data.byteLength,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(frame2Buffer, 0, frame2Data as unknown as Uint32Array<ArrayBuffer>);++ const flowBuffer = this.device.createBuffer({+ size: flowField.vectors.byteLength,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,+ });+ this.device.queue.writeBuffer(flowBuffer, 0, flowField.vectors as unknown as Float32Array<ArrayBuffer>);++ const outputSize = width * height * 4;+ const outputBuffer = this.device.createBuffer({+ size: outputSize,+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,+ });++ const bindGroup = this.device.createBindGroup({+ layout: this.warpBlendPipeline.getBindGroupLayout(0),+ entries: [+ { binding: 0, resource: { buffer: paramsBuffer } },+ { binding: 1, resource: { buffer: frame1Buffer } },+ { binding: 2, resource: { buffer: frame2Buffer } },+ { binding: 3, resource: { buffer: flowBuffer } },+ { binding: 4, resource: { buffer: outputBuffer } },+ ],+ });++ const encoder = this.device.createCommandEncoder();+ const pass = encoder.beginComputePass();+ pass.setPipeline(this.warpBlendPipeline);+ pass.setBindGroup(0, bindGroup);+ pass.dispatchWorkgroups(Math.ceil(width / 16), Math.ceil(height / 16));+ pass.end();++ const readBuffer = this.device.createBuffer({+ size: outputSize,+ usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,+ });+ encoder.copyBufferToBuffer(outputBuffer, 0, readBuffer, 0, outputSize);++ this.device.queue.submit([encoder.finish()]);++ await readBuffer.mapAsync(GPUMapMode.READ);+ const result = new Uint32Array(readBuffer.getMappedRange().slice(0));+ readBuffer.unmap();++ paramsBuffer.destroy();+ frame1Buffer.destroy();+ frame2Buffer.destroy();+ flowBuffer.destroy();+ outputBuffer.destroy();+ readBuffer.destroy();++ return result;+ }++ dispose(): void {+ this.device?.destroy();+ this.device = null;+ this.blockMatchPipeline = null;+ this.warpBlendPipeline = null;+ }+}diff --git a/packages/core/src/video/frame-interpolation/types.ts b/packages/core/src/video/frame-interpolation/types.tsnew file mode 100644index 00000000..0146cc09--- /dev/null+++ b/packages/core/src/video/frame-interpolation/types.ts@@ -0,0 +1,29 @@+export interface FlowField {+ width: number;+ height: number;+ vectors: Float32Array;+}++export interface InterpolationConfig {+ quality: "low" | "medium" | "high";+ blockSize: number;+ searchRadius: number;+ pyramidLevels: number;+}++export interface FrameInterpolationResult {+ frame: ImageBitmap;+ computeTimeMs: number;+ method: "optical-flow" | "blend";+}++export const INTERPOLATION_QUALITY_PRESETS: Record<string, InterpolationConfig> = {+ low: { quality: "low", blockSize: 16, searchRadius: 16, pyramidLevels: 2 },+ medium: {+ quality: "medium",+ blockSize: 8,+ searchRadius: 24,+ pyramidLevels: 3,+ },+ high: { quality: "high", blockSize: 8, searchRadius: 32, pyramidLevels: 4 },+};diff --git a/packages/core/src/video/index.ts b/packages/core/src/video/index.tsindex d9855c4a..81dd224b 100644--- a/packages/core/src/video/index.ts+++ b/packages/core/src/video/index.ts@@ -9,6 +9,7 @@ export * from "./mask-engine";export * from "./composite-engine";export * from "./speed-engine";export * from "./speed-presets";+export * from "./frame-interpolation";export * from "./keyframe-engine";export * from "./chroma-key-engine";export * from "./motion-tracking-engine";diff --git a/packages/core/src/video/speed-engine.ts b/packages/core/src/video/speed-engine.tsindex 8ab1f552..431018ef 100644--- a/packages/core/src/video/speed-engine.ts+++ b/packages/core/src/video/speed-engine.ts@@ -375,6 +375,33 @@ export class SpeedEngine {const data = this.clipSpeedData.get(clipId);return data?.pitchCorrection ?? true;}++ getInterpolationInfo(+ clipId: string,+ playbackTime: number,+ sourceFrameRate: number,+ ): {+ needsInterpolation: boolean;+ frameBefore: number;+ frameAfter: number;+ t: number;+ } {+ const sourceTime = this.getSourceTimeAtPlaybackTime(clipId, playbackTime);+ const frameDuration = 1 / sourceFrameRate;+ const exactFrame = sourceTime / frameDuration;+ const frameBeforeIndex = Math.floor(exactFrame);+ const frameAfterIndex = frameBeforeIndex + 1;+ const t = exactFrame - frameBeforeIndex;++ const needsInterpolation = t > 0.01 && t < 0.99;++ return {+ needsInterpolation,+ frameBefore: frameBeforeIndex * frameDuration,+ frameAfter: frameAfterIndex * frameDuration,+ t,+ };+ }private getOrCreateSpeedData(clipId: string,originalDuration: number,diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.tsindex 3097b86c..1aefbfe1 100644--- a/packages/core/src/video/video-engine.ts+++ b/packages/core/src/video/video-engine.ts@@ -26,6 +26,7 @@ import type {PreloadRequest,} from "./types";import { getSpeedEngine } from "./speed-engine";+import { getFrameInterpolationEngine } from "./frame-interpolation";import {ParallelFrameDecoder,getParallelFrameDecoder,@@ -276,6 +277,68 @@ export class VideoEngine {}}+ private async decodeInterpolatedFrame(+ clip: Clip,+ mediaItem: MediaItem,+ _sourceTime: number,+ _timelineTime: number,+ width: number,+ height: number,+ ): Promise<ImageBitmap | null> {+ try {+ const frameRate = mediaItem.metadata?.frameRate ?? 30;+ const speedEngine = getSpeedEngine();+ const clipLocalTime = _timelineTime - clip.startTime;+ const interpInfo = speedEngine.getInterpolationInfo(+ clip.id,+ clipLocalTime,+ frameRate,+ );++ if (!interpInfo.needsInterpolation) return null;++ const timeBefore = clip.inPoint + interpInfo.frameBefore;+ const timeAfter = clip.inPoint + interpInfo.frameAfter;++ const frame1 = await this.decodeFrameWithMediaBunny(+ mediaItem.blob!,+ timeBefore,+ width,+ height,+ mediaItem.id,+ );+ const frame2 = await this.decodeFrameWithMediaBunny(+ mediaItem.blob!,+ timeAfter,+ width,+ height,+ mediaItem.id,+ );++ if (!frame1 || !frame2) return null;++ const engine = getFrameInterpolationEngine();+ const quality = clip.interpolationQuality ?? "medium";+ engine.setQuality(quality);++ const result = await engine.interpolate(+ frame1,+ frame2,+ interpInfo.t,+ mediaItem.id,+ timeBefore,+ timeAfter,+ );++ frame1.close();+ frame2.close();++ return result.frame;+ } catch {+ return null;+ }+ }+/*** Decode a frame using native video element (fallback method).*/@@ -506,13 +569,30 @@ export class VideoEngine {);}} else {- bitmap = await this.decodeFrameWithMediaBunny(- mediaItem.blob,- clipInfo.sourceTime,- settings.width,- settings.height,- clipInfo.mediaId,- );+ const effectiveSpeed = clip.speed ?? 1;+ const shouldInterpolate =+ clip.smoothSlowMo === true && effectiveSpeed < 1;++ if (shouldInterpolate && mediaItem.metadata?.frameRate) {+ bitmap = await this.decodeInterpolatedFrame(+ clip,+ mediaItem,+ clipInfo.sourceTime,+ time,+ settings.width,+ settings.height,+ );+ }++ if (!bitmap) {+ bitmap = await this.decodeFrameWithMediaBunny(+ mediaItem.blob,+ clipInfo.sourceTime,+ settings.width,+ settings.height,+ clipInfo.mediaId,+ );+ }if (!bitmap) {bitmap = await this.decodeFrameWithVideoElement(mediaItem.id,