Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat: add FFmpeg vidstab-based video stabilization

Augustus Otu1a37625d710a
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 6fc2e851..0567c2f6 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -25,6 +25,7 @@ import { useTimelineStore } from "../../stores/timeline-store";
import { useUIStore } from "../../stores/ui-store";
import { useThemeStore } from "../../stores/theme-store";
import { getRenderBridge } from "../../bridges/render-bridge";
+import { getEffectsBridge } from "../../bridges/effects-bridge";
import {
RendererFactory,
type Renderer,
@@ -67,7 +68,12 @@ import {
ParticleRenderer,
} from "./preview/index";
import { ProcessingOverlay } from "./ProcessingOverlay";
-import { getPersonSegmentationEngine, getBackgroundRemovalEngine, getStabilizationEngine } from "@openreel/core";
+import {
+ getPersonSegmentationEngine,
+ getBackgroundRemovalEngine,
+ getStabilizedTransform,
+ getVidstabEngine,
+} from "@openreel/core";
import type { MotionPathConfig, GSAPMotionPathPoint } from "@openreel/core";
interface GPULayer {
@@ -75,6 +81,107 @@ interface GPULayer {
transform: ClipTransform;
}
+interface PreparedPreviewFrame {
+ frame: ImageBitmap | HTMLCanvasElement | OffscreenCanvas;
+ cleanup: () => void;
+}
+
+const clipNeedsFrameProcessing = (clipId: string): boolean => {
+ const bgEngine = getBackgroundRemovalEngine();
+ if (bgEngine?.isInitialized() && bgEngine.getSettings(clipId).enabled) {
+ return true;
+ }
+
+ const effectsBridge = getEffectsBridge();
+ if (!effectsBridge.isInitialized()) {
+ return false;
+ }
+
+ if (effectsBridge.getEffects(clipId).some((effect) => effect.enabled)) {
+ return true;
+ }
+
+ return Object.keys(effectsBridge.getColorGrading(clipId)).length > 0;
+};
+
+const preparePreviewFrame = async (
+ clipId: string,
+ frameCanvas: HTMLCanvasElement | OffscreenCanvas,
+ preferBitmap: boolean,
+): Promise<PreparedPreviewFrame> => {
+ const needsProcessing = clipNeedsFrameProcessing(clipId);
+ if (!preferBitmap && !needsProcessing) {
+ return {
+ frame: frameCanvas,
+ cleanup: () => {},
+ };
+ }
+
+ let frameBitmap: ImageBitmap | null = null;
+ let processedFrame: ImageBitmap | null = null;
+
+ try {
+ frameBitmap = await createImageBitmap(frameCanvas);
+
+ if (!needsProcessing) {
+ return {
+ frame: frameBitmap,
+ cleanup: () => {
+ frameBitmap?.close();
+ },
+ };
+ }
+
+ processedFrame = await applyEffectsToFrame(clipId, frameBitmap);
+ if (processedFrame === frameBitmap) {
+ return {
+ frame: frameBitmap,
+ cleanup: () => {
+ frameBitmap?.close();
+ },
+ };
+ }
+
+ return {
+ frame: processedFrame,
+ cleanup: () => {
+ processedFrame?.close();
+ frameBitmap?.close();
+ },
+ };
+ } catch {
+ processedFrame?.close();
+ frameBitmap?.close();
+
+ return {
+ frame: frameCanvas,
+ cleanup: () => {},
+ };
+ }
+};
+
+const applyStabilizationTransform = (
+ clip: Track["clips"][number],
+ transform: ClipTransform,
+ sourceTime: number,
+ canvasWidth: number,
+ canvasHeight: number,
+ frameWidth: number,
+ frameHeight: number,
+): ClipTransform => {
+ return getStabilizedTransform(
+ clip,
+ transform,
+ sourceTime,
+ {
+ canvasWidth,
+ canvasHeight,
+ sourceWidth: frameWidth,
+ sourceHeight: frameHeight,
+ },
+ ) as ClipTransform;
+};
+
const renderFrameWithGPU = async (
renderer: Renderer,
frame: ImageBitmap,
@@ -1220,7 +1327,10 @@ export const Preview: React.FC = () => {
): Promise<ImageBitmap | null> => {
const mediaItem = getMediaItem(clip.mediaId);
if (!mediaItem?.blob) return null;
- const mediaBlob = mediaItem.blob;
+ const vidstab = getVidstabEngine();
+ const mediaBlob = (vidstab.hasStabilized(clip.id)
+ ? vidstab.getStabilizedBlob(clip.id)
+ : mediaItem.blob)!;
if (mediaItem.type === "image") {
try {
@@ -1265,7 +1375,8 @@ export const Preview: React.FC = () => {
);
const mediaTime = (clip.inPoint || 0) + adjustedLocalTime;
- const cacheKey = clip.mediaId;
+ const isStabilized = vidstab.hasStabilized(clip.id);
+ const cacheKey = isStabilized ? `${clip.mediaId}:stabilized` : clip.mediaId;
let cached = videoElementCacheRef.current.get(cacheKey);
if (!cached) {
@@ -1723,6 +1834,15 @@ export const Preview: React.FC = () => {
if (frame) {
const clipLocalTime = time - clip.startTime;
+ const speedEngine = getSpeedEngine();
+ const adjustedLocalTime = speedEngine.getSourceTimeAtPlaybackTime(
+ clip.id,
+ clipLocalTime,
+ );
+ const sourceTime = Math.max(
+ clip.inPoint,
+ Math.min(clip.outPoint, clip.inPoint + adjustedLocalTime),
+ );
let animatedTransform = getAnimatedTransform(
clip.transform as ClipTransform,
clip.keyframes,
@@ -1764,6 +1884,16 @@ export const Preview: React.FC = () => {
};
}
+ const stabilizedTransform = applyStabilizationTransform(
+ clip,
+ animatedTransform,
+ sourceTime,
+ canvas.width,
+ canvas.height,
+ frame.width,
+ frame.height,
+ );
+
let processedFrame: ImageBitmap | null = null;
try {
processedFrame = await applyEffectsToFrame(clip.id, frame);
@@ -1771,7 +1901,7 @@ export const Preview: React.FC = () => {
drawFrameWithTransform(
ctx,
processedFrame,
- animatedTransform,
+ stabilizedTransform,
canvas.width,
canvas.height,
);
@@ -1780,7 +1910,7 @@ export const Preview: React.FC = () => {
drawFrameWithTransform(
ctx,
frame,
- animatedTransform,
+ stabilizedTransform,
canvas.width,
canvas.height,
);
@@ -1790,7 +1920,7 @@ export const Preview: React.FC = () => {
drawFrameWithTransform(
ctx,
frame,
- animatedTransform,
+ stabilizedTransform,
canvas.width,
canvas.height,
);
@@ -2227,7 +2357,11 @@ export const Preview: React.FC = () => {
return Promise.resolve();
}
- const url = URL.createObjectURL(mediaItem.blob);
+ const vidstabEng = getVidstabEngine();
+ const playBlob = (vidstabEng.hasStabilized(clip.id)
+ ? vidstabEng.getStabilizedBlob(clip.id)
+ : mediaItem.blob)!;
+ const url = URL.createObjectURL(playBlob);
const video = document.createElement("video");
video.src = url;
video.muted = true;
@@ -2476,13 +2610,6 @@ export const Preview: React.FC = () => {
}
}
- const clipLocalTime = currentPlayhead - clip.startTime;
- const targetMediaTime = (clip.inPoint || 0) + clipLocalTime;
- const drift = Math.abs(video.currentTime - targetMediaTime);
- if (drift > 0.1) {
- video.currentTime = targetMediaTime;
- }
-
const latestClip = (() => {
for (const track of timelineTracksRef.current) {
const found = track.clips.find((c) => c.id === clip.id);
@@ -2491,6 +2618,21 @@ export const Preview: React.FC = () => {
return clip;
})();
+ const clipLocalTime = currentPlayhead - latestClip.startTime;
+ const speedEngine = getSpeedEngine();
+ const adjustedLocalTime = speedEngine.getSourceTimeAtPlaybackTime(
+ latestClip.id,
+ clipLocalTime,
+ );
+ const sourceTime = Math.max(
+ latestClip.inPoint,
+ Math.min(latestClip.outPoint, latestClip.inPoint + adjustedLocalTime),
+ );
+ const drift = Math.abs(video.currentTime - sourceTime);
+ if (drift > 0.1) {
+ video.currentTime = sourceTime;
+ }
+
let transform = getAnimatedTransform(
(latestClip.transform as ClipTransform) || DEFAULT_TRANSFORM,
latestClip.keyframes,
@@ -2583,23 +2725,21 @@ export const Preview: React.FC = () => {
}
let finalTransform = transform;
- if (latestClip.stabilization?.enabled && latestClip.stabilization.analyzed) {
- const stabEngine = getStabilizationEngine();
- const correction = stabEngine.getCorrectionTransform(clip.id, clipLocalTime);
- if (correction) {
- finalTransform = {
- ...transform,
- position: {
- x: transform.position.x + correction.dx,
- y: transform.position.y + correction.dy,
- },
- rotation: transform.rotation + (correction.rotation * 180) / Math.PI,
- scale: {
- x: transform.scale.x * correction.scale,
- y: transform.scale.y * correction.scale,
- },
- };
- }
+ const vidstabEng = getVidstabEngine();
+ if (
+ latestClip.stabilization?.enabled &&
+ latestClip.stabilization.analyzed &&
+ !vidstabEng.hasStabilized(latestClip.id)
+ ) {
+ finalTransform = applyStabilizationTransform(
+ latestClip,
+ transform,
+ sourceTime,
+ canvas.width,
+ canvas.height,
+ video.videoWidth,
+ video.videoHeight,
+ );
}
drawFrameWithTransform(ctx, videoFrame, finalTransform, canvas.width, canvas.height);
@@ -2990,28 +3130,30 @@ export const Preview: React.FC = () => {
};
}
- let processedFrame:
- | ImageBitmap
- | HTMLCanvasElement
- | OffscreenCanvas = frameCanvas;
- try {
- const frameBitmap = await createImageBitmap(frameCanvas);
- processedFrame = await applyEffectsToFrame(
- clip.id,
- frameBitmap,
- );
- } catch {}
-
const useGPU =
rendererRef.current && rendererRef.current.type === "webgpu";
+ const preparedFrame = await preparePreviewFrame(
+ clip.id,
+ frameCanvas,
+ Boolean(useGPU),
+ );
+ const stabilizedTransform = applyStabilizationTransform(
+ clip,
+ transform,
+ currentMediaTime,
+ canvas.width,
+ canvas.height,
+ preparedFrame.frame.width,
+ preparedFrame.frame.height,
+ );
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
- if (useGPU && processedFrame instanceof ImageBitmap) {
+ if (useGPU && preparedFrame.frame instanceof ImageBitmap) {
const gpuResult = await renderFrameWithGPU(
rendererRef.current!,
- processedFrame,
- transform,
+ preparedFrame.frame,
+ stabilizedTransform,
canvas.width,
canvas.height,
);
@@ -3021,8 +3163,8 @@ export const Preview: React.FC = () => {
} else {
drawFrameWithTransform(
ctx,
- processedFrame,
- transform,
+ preparedFrame.frame,
+ stabilizedTransform,
canvas.width,
canvas.height,
);
@@ -3030,12 +3172,13 @@ export const Preview: React.FC = () => {
} else {
drawFrameWithTransform(
ctx,
- processedFrame,
- transform,
+ preparedFrame.frame,
+ stabilizedTransform,
canvas.width,
canvas.height,
);
}
+ preparedFrame.cleanup();
const nowPh = performance.now();
if (nowPh - lastPlayheadUpdateRef.current >= PLAYHEAD_UPDATE_THROTTLE_MS) {
@@ -3418,6 +3561,17 @@ export const Preview: React.FC = () => {
const sortedClips = [...activeClips].sort(
(a, b) => b.trackIndex - a.trackIndex,
);
+ const activeShapeClips = getActiveShapeClips(
+ allShapeClipsRef.current,
+ currentPlayhead,
+ );
+ const activeTextClips = getActiveTextClips(
+ allTextClipsRef.current,
+ currentPlayhead,
+ );
+ const activeTextNeedsSubject = hasBehindSubjectText(activeTextClips);
+ const useGPUFrames =
+ rendererRef.current?.type === "webgpu" && !activeTextNeedsSubject;
const imageClipFrames: Array<{
clip: (typeof sortedClips)[0]["clip"];
@@ -3430,6 +3584,7 @@ export const Preview: React.FC = () => {
clip: (typeof sortedClips)[0]["clip"];
transform: ClipTransform;
frame: ImageBitmap | HTMLCanvasElement | OffscreenCanvas;
+ cleanup: () => void;
} | null>
> = [];
@@ -3495,7 +3650,10 @@ export const Preview: React.FC = () => {
clip.id,
clipLocalTime,
);
- const mediaTime = (clip.inPoint || 0) + adjustedLocalTime;
+ const sourceTime = Math.max(
+ clip.inPoint,
+ Math.min(clip.outPoint, (clip.inPoint || 0) + adjustedLocalTime),
+ );
try {
const frameResult = await (
@@ -3506,27 +3664,33 @@ export const Preview: React.FC = () => {
duration: number;
} | null>;
}
- ).getCanvas(mediaTime);
+ ).getCanvas(sourceTime);
if (!isActive) return null;
if (frameResult?.canvas) {
- let processedFrame:
- | ImageBitmap
- | HTMLCanvasElement
- | OffscreenCanvas = frameResult.canvas;
-
- try {
- const frameBitmap = await createImageBitmap(
- frameResult.canvas,
- );
- processedFrame = await applyEffectsToFrame(
- clip.id,
- frameBitmap,
- );
- } catch {}
+ const preparedFrame = await preparePreviewFrame(
+ clip.id,
+ frameResult.canvas,
+ useGPUFrames,
+ );
- return { clip, transform, frame: processedFrame };
+ const stabilizedTransform = applyStabilizationTransform(
+ clip,
+ transform,
+ sourceTime,
+ canvas.width,
+ canvas.height,
+ preparedFrame.frame.width,
+ preparedFrame.frame.height,
+ );
+
+ return {
+ clip,
+ transform: stabilizedTransform,
+ frame: preparedFrame.frame,
+ cleanup: preparedFrame.cleanup,
+ };
}
} catch (error) {
const errorMessage =
@@ -3559,14 +3723,6 @@ export const Preview: React.FC = () => {
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
- const activeShapeClips = getActiveShapeClips(
- allShapeClipsRef.current,
- currentPlayhead,
- );
- const activeTextClips = getActiveTextClips(
- allTextClipsRef.current,
- currentPlayhead,
- );
const tracks = timelineTracksRef.current;
const clipToTrackIndex = new Map<string, number>();
@@ -3593,7 +3749,6 @@ export const Preview: React.FC = () => {
)
.sort((a, b) => b.originalIndex - a.originalIndex);
- const activeTextNeedsSubject = hasBehindSubjectText(activeTextClips);
const useGPU =
rendererRef.current &&
rendererRef.current.type === "webgpu" &&
@@ -3759,6 +3914,10 @@ export const Preview: React.FC = () => {
subjectFrame?.close();
}
+ for (const frame of validVideoFrames) {
+ frame.cleanup();
+ }
+
const activeSubtitles = getActiveSubtitles(
allSubtitlesRef.current,
currentPlayhead,
diff --git a/apps/web/src/components/editor/inspector/StabilizationSection.tsx b/apps/web/src/components/editor/inspector/StabilizationSection.tsx
index 83e0d176..94351a09 100644
--- a/apps/web/src/components/editor/inspector/StabilizationSection.tsx
+++ b/apps/web/src/components/editor/inspector/StabilizationSection.tsx
@@ -1,7 +1,7 @@
import React, { useState, useCallback } from "react";
-import { Video } from "lucide-react";
+import { Video, Download } from "lucide-react";
import type { Clip } from "@openreel/core";
-import { getStabilizationEngine } from "@openreel/core";
+import { getVidstabEngine, type VidstabProgress } from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { Switch, Label, Slider, Button } from "@openreel/ui";
@@ -13,7 +13,8 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({
clip,
}) => {
const { project, getMediaItem } = useProjectStore();
- const [analyzing, setAnalyzing] = useState(false);
+ const [processing, setProcessing] = useState(false);
+ const [stage, setStage] = useState<VidstabProgress["stage"] | null>(null);
const [progress, setProgress] = useState(0);
const stabilization = clip.stabilization ?? {
@@ -23,6 +24,9 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({
analyzed: false,
};
+ const vidstabEngine = getVidstabEngine();
+ const isStabilized = vidstabEngine.hasStabilized(clip.id);
+
const updateStabilization = useCallback(
(updates: Partial<typeof stabilization>) => {
const newStabilization = { ...stabilization, ...updates };
@@ -51,78 +55,95 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({
[clip.id, project, stabilization],
);
- const handleAnalyze = useCallback(async () => {
+ const handleStabilize = useCallback(async () => {
const mediaItem = getMediaItem(clip.mediaId);
if (!mediaItem?.blob) return;
- setAnalyzing(true);
+ setProcessing(true);
setProgress(0);
+ setStage("downloading");
try {
- const url = URL.createObjectURL(mediaItem.blob);
- const video = document.createElement("video");
- video.src = url;
- video.muted = true;
- video.preload = "auto";
- video.crossOrigin = "anonymous";
-
- await new Promise<void>((resolve, reject) => {
- video.onloadedmetadata = () => resolve();
- video.onerror = () => reject(new Error("Failed to load video"));
- setTimeout(() => reject(new Error("Timeout")), 10000);
+ await vidstabEngine.load((p) => {
+ setStage(p.stage);
+ setProgress(Math.round(p.progress * 100));
});
- const duration = clip.outPoint - clip.inPoint;
- const stabEngine = getStabilizationEngine();
+ setStage("detecting");
+ setProgress(0);
- await stabEngine.analyzeClip(
+ await vidstabEngine.stabilize(
clip.id,
- video,
- duration,
+ mediaItem.blob,
{
strength: stabilization.strength,
cropMode: stabilization.cropMode,
- analysisInterval: 2,
+ analysisInterval: 1,
+ },
+ (p) => {
+ setStage(p.stage);
+ setProgress(Math.round(p.progress * 100));
},
- (p) => setProgress(Math.round(p * 100)),
);
- video.src = "";
- URL.revokeObjectURL(url);
-
updateStabilization({ enabled: true, analyzed: true });
} catch (error) {
- console.warn("Stabilization analysis failed:", error);
+ console.warn("Stabilization failed:", error);
} finally {
- setAnalyzing(false);
+ setProcessing(false);
+ setStage(null);
}
- }, [clip.id, clip.mediaId, clip.outPoint, clip.inPoint, getMediaItem, stabilization.strength, stabilization.cropMode, updateStabilization]);
+ }, [
+ clip.id,
+ clip.mediaId,
+ getMediaItem,
+ vidstabEngine,
+ stabilization.strength,
+ stabilization.cropMode,
+ updateStabilization,
+ ]);
const handleToggle = useCallback(
(enabled: boolean) => {
- if (enabled && !stabilization.analyzed) {
- handleAnalyze();
+ if (enabled && !isStabilized) {
+ handleStabilize();
return;
}
updateStabilization({ enabled });
},
- [stabilization.analyzed, handleAnalyze, updateStabilization],
+ [isStabilized, handleStabilize, updateStabilization],
);
const handleStrengthChange = useCallback(
(value: number[]) => {
const strength = value[0];
- updateStabilization({ strength });
-
- if (stabilization.analyzed) {
- const stabEngine = getStabilizationEngine();
- stabEngine.removeProfile(clip.id);
- updateStabilization({ strength, analyzed: false, enabled: false });
+ if (isStabilized) {
+ vidstabEngine.removeStabilized(clip.id);
+ updateStabilization({
+ strength,
+ analyzed: false,
+ enabled: false,
+ });
+ return;
}
+ updateStabilization({ strength });
},
- [clip.id, stabilization.analyzed, updateStabilization],
+ [clip.id, isStabilized, vidstabEngine, updateStabilization],
);
+ const stageLabel = (() => {
+ switch (stage) {
+ case "downloading":
+ return "Downloading stabilization engine...";
+ case "detecting":
+ return "Analyzing motion...";
+ case "stabilizing":
+ return "Stabilizing video...";
+ default:
+ return "";
+ }
+ })();
+
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
@@ -131,9 +152,9 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({
Stabilize
</Label>
<Switch
- checked={stabilization.enabled}
+ checked={stabilization.enabled && isStabilized}
onCheckedChange={handleToggle}
- disabled={analyzing}
+ disabled={processing}
/>
</div>
@@ -146,18 +167,25 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({
</div>
<Slider
value={[stabilization.strength]}
- min={0}
+ min={10}
max={100}
- step={1}
+ step={5}
onValueChange={handleStrengthChange}
- disabled={analyzing}
+ disabled={processing}
/>
</div>
- {analyzing && (
+ {!vidstabEngine.isLoaded() && !processing && !isStabilized && (
+ <div className="flex items-center gap-2 rounded-md border border-border/60 bg-muted/40 px-3 py-2 text-[11px] text-muted-foreground">
+ <Download className="h-3.5 w-3.5 shrink-0" />
+ <span>First use requires a one-time download (~65 MB)</span>
+ </div>
+ )}
+
+ {processing && stage && (
<div className="space-y-1">
<div className="flex items-center justify-between text-xs text-muted-foreground">
- <span>Analyzing motion...</span>
+ <span>{stageLabel}</span>
<span>{progress}%</span>
</div>
<div className="h-1.5 w-full rounded-full bg-muted">
@@ -169,14 +197,14 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({
</div>
)}
- {stabilization.analyzed && !analyzing && (
+ {isStabilized && !processing && (
<Button
variant="outline"
size="sm"
className="w-full"
- onClick={handleAnalyze}
+ onClick={handleStabilize}
>
- Re-analyze
+ Re-stabilize
</Button>
)}
</div>
diff --git a/packages/core/src/video/stabilization/index.ts b/packages/core/src/video/stabilization/index.ts
index a96c0dc3..42bd708f 100644
--- a/packages/core/src/video/stabilization/index.ts
+++ b/packages/core/src/video/stabilization/index.ts
@@ -3,10 +3,21 @@ export type {
CorrectionTransform,
StabilizationProfile,
StabilizationConfig,
+ StabilizationRenderContext,
+} from "./types";
+export {
+ DEFAULT_STABILIZATION_CONFIG,
+ STABILIZATION_ANALYSIS_VERSION,
} from "./types";
-export { DEFAULT_STABILIZATION_CONFIG } from "./types";
export {
StabilizationEngine,
getStabilizationEngine,
disposeStabilizationEngine,
+ getStabilizedTransform,
} from "./stabilization-engine";
+export type { VidstabProgress } from "./vidstab-engine";
+export {
+ VidstabEngine,
+ getVidstabEngine,
+ disposeVidstabEngine,
+} from "./vidstab-engine";
diff --git a/packages/core/src/video/stabilization/vidstab-engine.ts b/packages/core/src/video/stabilization/vidstab-engine.ts
new file mode 100644
index 00000000..6d9faaf4
--- /dev/null
+++ b/packages/core/src/video/stabilization/vidstab-engine.ts
@@ -0,0 +1,212 @@
+import type { StabilizationConfig } from "./types";
+import { DEFAULT_STABILIZATION_CONFIG } from "./types";
+
+type FFmpegInstance = {
+ load(options?: {
+ coreURL?: string;
+ wasmURL?: string;
+ workerURL?: string;
+ }): Promise<void>;
+ writeFile(name: string, data: Uint8Array | string): Promise<void>;
+ readFile(name: string): Promise<Uint8Array>;
+ deleteFile(name: string): Promise<void>;
+ exec(args: string[]): Promise<number>;
+ on(
+ event: string,
+ callback: (data: { progress?: number; time?: number; message?: string; type?: string }) => void,
+ ): void;
+ off(
+ event: string,
+ callback?: (data: { progress?: number; time?: number; message?: string; type?: string }) => void,
+ ): void;
+ terminate(): void;
+};
+
+const VIDSTAB_CORE_CDN = {
+ mt: "https://unpkg.com/@willyjl/[email protected]/dist/esm",
+ st: "https://unpkg.com/@willyjl/[email protected]/dist/esm",
+};
+
+export type VidstabProgress = {
+ stage: "downloading" | "detecting" | "stabilizing";
+ progress: number;
+};
+
+export class VidstabEngine {
+ private ffmpeg: FFmpegInstance | null = null;
+ private loaded = false;
+ private loading: Promise<void> | null = null;
+ private stabilizedBlobs: Map<string, Blob> = new Map();
+
+ async load(onProgress?: (progress: VidstabProgress) => void): Promise<void> {
+ if (this.loaded) return;
+ if (this.loading) return this.loading;
+
+ this.loading = this.doLoad(onProgress);
+ await this.loading;
+ }
+
+ private async doLoad(onProgress?: (progress: VidstabProgress) => void): Promise<void> {
+ try {
+ const { FFmpeg } = await import("@ffmpeg/ffmpeg");
+ const { toBlobURL } = await import("@ffmpeg/util");
+
+ this.ffmpeg = new FFmpeg() as unknown as FFmpegInstance;
+
+ onProgress?.({ stage: "downloading", progress: 0 });
+
+ const useMultiThread =
+ typeof crossOriginIsolated !== "undefined" && crossOriginIsolated;
+
+ const baseURL = useMultiThread ? VIDSTAB_CORE_CDN.mt : VIDSTAB_CORE_CDN.st;
+
+ if (useMultiThread) {
+ const [coreURL, wasmURL, workerURL] = await Promise.all([
+ toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
+ toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
+ toBlobURL(`${baseURL}/ffmpeg-core.worker.js`, "text/javascript"),
+ ]);
+
+ onProgress?.({ stage: "downloading", progress: 0.9 });
+
+ await this.ffmpeg.load({ coreURL, wasmURL, workerURL });
+ } else {
+ const [coreURL, wasmURL] = await Promise.all([
+ toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
+ toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
+ ]);
+
+ onProgress?.({ stage: "downloading", progress: 0.9 });
+
+ await this.ffmpeg.load({ coreURL, wasmURL });
+ }
+
+ onProgress?.({ stage: "downloading", progress: 1 });
+ this.loaded = true;
+ } catch (error) {
+ this.loading = null;
+ throw new Error(
+ `Failed to load FFmpeg vidstab core: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
+ isLoaded(): boolean {
+ return this.loaded && this.ffmpeg !== null;
+ }
+
+ hasStabilized(clipId: string): boolean {
+ return this.stabilizedBlobs.has(clipId);
+ }
+
+ getStabilizedBlob(clipId: string): Blob | null {
+ return this.stabilizedBlobs.get(clipId) ?? null;
+ }
+
+ async stabilize(
+ clipId: string,
+ sourceBlob: Blob,
+ config: StabilizationConfig = DEFAULT_STABILIZATION_CONFIG,
+ onProgress?: (progress: VidstabProgress) => void,
+ ): Promise<Blob> {
+ if (!this.ffmpeg || !this.loaded) {
+ throw new Error("VidstabEngine not loaded. Call load() first.");
+ }
+
+ const inputData = new Uint8Array(await sourceBlob.arrayBuffer());
+ await this.ffmpeg.writeFile("input.mp4", inputData);
+
+ const shakiness = Math.max(1, Math.min(10, Math.round(config.strength / 10)));
+ const smoothing = Math.max(1, Math.round((config.strength / 100) * 30));
+ const zoom = config.cropMode === "auto" ? -1 : 0;
+
+ let progressHandler: ((data: { progress?: number }) => void) | null = null;
+
+ progressHandler = (data: { progress?: number }) => {
+ if (data.progress !== undefined) {
+ onProgress?.({ stage: "detecting", progress: data.progress });
+ }
+ };
+ this.ffmpeg.on("progress", progressHandler);
+
+ const detectResult = await this.ffmpeg.exec([
+ "-i", "input.mp4",
+ "-vf", `vidstabdetect=shakiness=${shakiness}:accuracy=15:result=transforms.trf`,
+ "-f", "null",
+ "-",
+ ]);
+
+ if (detectResult !== 0) {
+ this.ffmpeg.off("progress", progressHandler);
+ await this.cleanup();
+ throw new Error("vidstabdetect failed");
+ }
+
+ this.ffmpeg.off("progress", progressHandler);
+
+ progressHandler = (data: { progress?: number }) => {
+ if (data.progress !== undefined) {
+ onProgress?.({ stage: "stabilizing", progress: data.progress });
+ }
+ };
+ this.ffmpeg.on("progress", progressHandler);
+
+ const transformResult = await this.ffmpeg.exec([
+ "-i", "input.mp4",
+ "-vf", `vidstabtransform=input=transforms.trf:smoothing=${smoothing}:zoom=${zoom}:interpol=bicubic`,
+ "-c:a", "copy",
+ "output.mp4",
+ ]);
+
+ this.ffmpeg.off("progress", progressHandler);
+
+ if (transformResult !== 0) {
+ await this.cleanup();
+ throw new Error("vidstabtransform failed");
+ }
+
+ const outputData = await this.ffmpeg.readFile("output.mp4");
+ const stabilizedBlob = new Blob([outputData.buffer as ArrayBuffer], { type: "video/mp4" });
+
+ this.stabilizedBlobs.set(clipId, stabilizedBlob);
+
+ await this.cleanup();
+
+ return stabilizedBlob;
+ }
+
+ private async cleanup(): Promise<void> {
+ if (!this.ffmpeg) return;
+ try { await this.ffmpeg.deleteFile("input.mp4"); } catch {}
+ try { await this.ffmpeg.deleteFile("output.mp4"); } catch {}
+ try { await this.ffmpeg.deleteFile("transforms.trf"); } catch {}
+ }
+
+ removeStabilized(clipId: string): void {
+ this.stabilizedBlobs.delete(clipId);
+ }
+
+ dispose(): void {
+ this.stabilizedBlobs.clear();
+ if (this.ffmpeg) {
+ this.ffmpeg.terminate();
+ this.ffmpeg = null;
+ }
+ this.loaded = false;
+ this.loading = null;
+ }
+}
+
+let vidstabEngineInstance: VidstabEngine | null = null;
+
+export function getVidstabEngine(): VidstabEngine {
+ if (!vidstabEngineInstance) {
+ vidstabEngineInstance = new VidstabEngine();
+ }
+ return vidstabEngineInstance;
+}
+
+export function disposeVidstabEngine(): void {
+ vidstabEngineInstance?.dispose();
+ vidstabEngineInstance = null;
+}
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index 011debf6..73b85565 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -27,7 +27,10 @@ import type {
} from "./types";
import { getSpeedEngine } from "./speed-engine";
import { getFrameInterpolationEngine } from "./frame-interpolation";
-import { getStabilizationEngine } from "./stabilization";
+import {
+ getStabilizedTransform,
+ getVidstabEngine,
+} from "./stabilization";
import {
ParallelFrameDecoder,
getParallelFrameDecoder,
@@ -765,28 +768,20 @@ export class VideoEngine {
}
}
- let drawTransform = scaledTransform;
- if (clip.stabilization?.enabled && clip.stabilization.analyzed) {
- const stabEngine = getStabilizationEngine();
- const correction = stabEngine.getCorrectionTransform(
- clip.id,
- clipInfo.sourceTime,
- );
- if (correction) {
- drawTransform = {
- ...scaledTransform,
- position: {
- x: scaledTransform.position.x + correction.dx,
- y: scaledTransform.position.y + correction.dy,
- },
- rotation: scaledTransform.rotation + (correction.rotation * 180) / Math.PI,
- scale: {
- x: scaledTransform.scale.x * correction.scale,
- y: scaledTransform.scale.y * correction.scale,
+ const vidstabEng = getVidstabEngine();
+ const drawTransform = vidstabEng.hasStabilized(clip.id)
+ ? scaledTransform
+ : getStabilizedTransform(
+ clip,
+ scaledTransform,
+ clipInfo.sourceTime,
+ {
+ canvasWidth: width,
+ canvasHeight: height,
+ sourceWidth: processedBitmap.width,
+ sourceHeight: processedBitmap.height,
},
- };
- }
- }
+ );
this.drawFrameToContext(
ctx,
diff --git a/scripts/upload-vidstab-r2.sh b/scripts/upload-vidstab-r2.sh
new file mode 100755
index 00000000..11d7fc30
--- /dev/null
+++ b/scripts/upload-vidstab-r2.sh
@@ -0,0 +1,21 @@
+#!/bin/bash
+# Upload FFmpeg vidstab core files to Cloudflare R2
+# Bucket: pub-openreel (or your bucket name)
+# Path prefix: ffmpeg-vidstab/
+
+BUCKET="pub-openreel"
+MT_DIR="/tmp/vidstab/mt/dist/esm"
+ST_DIR="/tmp/vidstab/st/dist/esm"
+
+echo "Uploading multi-threaded core..."
+wrangler r2 object put "$BUCKET/ffmpeg-vidstab/mt/ffmpeg-core.js" --file "$MT_DIR/ffmpeg-core.js" --content-type "text/javascript"
+wrangler r2 object put "$BUCKET/ffmpeg-vidstab/mt/ffmpeg-core.wasm" --file "$MT_DIR/ffmpeg-core.wasm" --content-type "application/wasm"
+wrangler r2 object put "$BUCKET/ffmpeg-vidstab/mt/ffmpeg-core.worker.js" --file "$MT_DIR/ffmpeg-core.worker.js" --content-type "text/javascript"
+
+echo "Uploading single-threaded core..."
+wrangler r2 object put "$BUCKET/ffmpeg-vidstab/st/ffmpeg-core.js" --file "$ST_DIR/ffmpeg-core.js" --content-type "text/javascript"
+wrangler r2 object put "$BUCKET/ffmpeg-vidstab/st/ffmpeg-core.wasm" --file "$ST_DIR/ffmpeg-core.wasm" --content-type "application/wasm"
+
+echo "Done! Files available at:"
+echo " https://pub-openreel.r2.dev/ffmpeg-vidstab/mt/"
+echo " https://pub-openreel.r2.dev/ffmpeg-vidstab/st/"