OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: add video stabilization with optical flow motion analysis
Augustus Otucc11544ac45b
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsxindex 4ab8edd5..2cd04466 100644--- a/apps/web/src/components/editor/InspectorPanel.tsx+++ b/apps/web/src/components/editor/InspectorPanel.tsx@@ -39,6 +39,7 @@ import {AutoCutSilenceSection,CropSection,SpeedSection,+ StabilizationSection,SpeedRampSection,MotionPresetsPanel,EmphasisAnimationSection,@@ -919,6 +920,22 @@ export const InspectorPanel: React.FC = () => {</Section>)}+ {/* Stabilization */}+ {showVideoControls &&+ selectedClip &&+ !selectedClip.mediaId.startsWith("text-") &&+ !selectedClip.mediaId.startsWith("shape-") &&+ !selectedClip.mediaId.startsWith("svg-") &&+ !selectedClip.mediaId.startsWith("sticker-") && (+ <Section+ title="Stabilization"+ sectionId="stabilization"+ defaultOpen={false}+ >+ <StabilizationSection clip={selectedClip as Clip} />+ </Section>+ )}+{/* Speed Curves */}{showVideoControls &&selectedClip &&diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex cdeed58b..6fc2e851 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -67,7 +67,7 @@ import {ParticleRenderer,} from "./preview/index";import { ProcessingOverlay } from "./ProcessingOverlay";-import { getPersonSegmentationEngine, getBackgroundRemovalEngine } from "@openreel/core";+import { getPersonSegmentationEngine, getBackgroundRemovalEngine, getStabilizationEngine } from "@openreel/core";import type { MotionPathConfig, GSAPMotionPathPoint } from "@openreel/core";interface GPULayer {@@ -2582,7 +2582,27 @@ export const Preview: React.FC = () => {}}- drawFrameWithTransform(ctx, videoFrame, transform, canvas.width, canvas.height);+ 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,+ },+ };+ }+ }++ drawFrameWithTransform(ctx, videoFrame, finalTransform, canvas.width, canvas.height);if (videoFrame !== video && videoFrame instanceof ImageBitmap) {videoFrame.close();}diff --git a/apps/web/src/components/editor/inspector/StabilizationSection.tsx b/apps/web/src/components/editor/inspector/StabilizationSection.tsxnew file mode 100644index 00000000..83e0d176--- /dev/null+++ b/apps/web/src/components/editor/inspector/StabilizationSection.tsx@@ -0,0 +1,184 @@+import React, { useState, useCallback } from "react";+import { Video } from "lucide-react";+import type { Clip } from "@openreel/core";+import { getStabilizationEngine } from "@openreel/core";+import { useProjectStore } from "../../../stores/project-store";+import { Switch, Label, Slider, Button } from "@openreel/ui";++interface StabilizationSectionProps {+ clip: Clip;+}++export const StabilizationSection: React.FC<StabilizationSectionProps> = ({+ clip,+}) => {+ const { project, getMediaItem } = useProjectStore();+ const [analyzing, setAnalyzing] = useState(false);+ const [progress, setProgress] = useState(0);++ const stabilization = clip.stabilization ?? {+ enabled: false,+ strength: 50,+ cropMode: "auto" as const,+ analyzed: false,+ };++ const updateStabilization = useCallback(+ (updates: Partial<typeof stabilization>) => {+ const newStabilization = { ...stabilization, ...updates };++ 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],+ stabilization: newStabilization,+ };+ const newClips = [...track.clips];+ newClips[clipIndex] = updatedClip;+ return { ...track, clips: newClips };+ });++ useProjectStore.setState({+ project: {+ ...project,+ timeline: { ...project.timeline, tracks },+ modifiedAt: Date.now(),+ },+ });+ },+ [clip.id, project, stabilization],+ );++ const handleAnalyze = useCallback(async () => {+ const mediaItem = getMediaItem(clip.mediaId);+ if (!mediaItem?.blob) return;++ setAnalyzing(true);+ setProgress(0);++ 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);+ });++ const duration = clip.outPoint - clip.inPoint;+ const stabEngine = getStabilizationEngine();++ await stabEngine.analyzeClip(+ clip.id,+ video,+ duration,+ {+ strength: stabilization.strength,+ cropMode: stabilization.cropMode,+ analysisInterval: 2,+ },+ (p) => setProgress(Math.round(p * 100)),+ );++ video.src = "";+ URL.revokeObjectURL(url);++ updateStabilization({ enabled: true, analyzed: true });+ } catch (error) {+ console.warn("Stabilization analysis failed:", error);+ } finally {+ setAnalyzing(false);+ }+ }, [clip.id, clip.mediaId, clip.outPoint, clip.inPoint, getMediaItem, stabilization.strength, stabilization.cropMode, updateStabilization]);++ const handleToggle = useCallback(+ (enabled: boolean) => {+ if (enabled && !stabilization.analyzed) {+ handleAnalyze();+ return;+ }+ updateStabilization({ enabled });+ },+ [stabilization.analyzed, handleAnalyze, 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 });+ }+ },+ [clip.id, stabilization.analyzed, updateStabilization],+ );++ return (+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <Label className="flex items-center gap-2 text-sm">+ <Video className="h-4 w-4" />+ Stabilize+ </Label>+ <Switch+ checked={stabilization.enabled}+ onCheckedChange={handleToggle}+ disabled={analyzing}+ />+ </div>++ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <Label className="text-xs text-muted-foreground">Strength</Label>+ <span className="text-xs text-muted-foreground">+ {stabilization.strength}%+ </span>+ </div>+ <Slider+ value={[stabilization.strength]}+ min={0}+ max={100}+ step={1}+ onValueChange={handleStrengthChange}+ disabled={analyzing}+ />+ </div>++ {analyzing && (+ <div className="space-y-1">+ <div className="flex items-center justify-between text-xs text-muted-foreground">+ <span>Analyzing motion...</span>+ <span>{progress}%</span>+ </div>+ <div className="h-1.5 w-full rounded-full bg-muted">+ <div+ className="h-full rounded-full bg-primary transition-all"+ style={{ width: `${progress}%` }}+ />+ </div>+ </div>+ )}++ {stabilization.analyzed && !analyzing && (+ <Button+ variant="outline"+ size="sm"+ className="w-full"+ onClick={handleAnalyze}+ >+ Re-analyze+ </Button>+ )}+ </div>+ );+};diff --git a/apps/web/src/components/editor/inspector/index.ts b/apps/web/src/components/editor/inspector/index.tsindex c85a40c4..3a89b743 100644--- a/apps/web/src/components/editor/inspector/index.ts+++ b/apps/web/src/components/editor/inspector/index.ts@@ -14,6 +14,7 @@ export { NoiseReductionSection } from "./NoiseReductionSection";export { BackgroundRemovalSection } from "./BackgroundRemovalSection";export { CropSection } from "./CropSection";export { SpeedSection } from "./SpeedSection";+export { StabilizationSection } from "./StabilizationSection";// Color Gradingexport { ColorGradingSection } from "./ColorGradingSection";diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.tsindex 3d4ccb1b..c633e463 100644--- a/packages/core/src/types/timeline.ts+++ b/packages/core/src/types/timeline.ts@@ -60,6 +60,12 @@ export interface Clip {readonly reversed?: boolean;readonly smoothSlowMo?: boolean;readonly interpolationQuality?: "low" | "medium" | "high";+ readonly stabilization?: {+ enabled: boolean;+ strength: number;+ cropMode: "auto" | "none";+ analyzed?: boolean;+ };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/index.ts b/packages/core/src/video/index.tsindex 81dd224b..4b62e967 100644--- a/packages/core/src/video/index.ts+++ b/packages/core/src/video/index.ts@@ -10,6 +10,7 @@ export * from "./composite-engine";export * from "./speed-engine";export * from "./speed-presets";export * from "./frame-interpolation";+export * from "./stabilization";export * from "./keyframe-engine";export * from "./chroma-key-engine";export * from "./motion-tracking-engine";diff --git a/packages/core/src/video/stabilization/index.ts b/packages/core/src/video/stabilization/index.tsnew file mode 100644index 00000000..a96c0dc3--- /dev/null+++ b/packages/core/src/video/stabilization/index.ts@@ -0,0 +1,12 @@+export type {+ MotionSample,+ CorrectionTransform,+ StabilizationProfile,+ StabilizationConfig,+} from "./types";+export { DEFAULT_STABILIZATION_CONFIG } from "./types";+export {+ StabilizationEngine,+ getStabilizationEngine,+ disposeStabilizationEngine,+} from "./stabilization-engine";diff --git a/packages/core/src/video/stabilization/motion-path.ts b/packages/core/src/video/stabilization/motion-path.tsnew file mode 100644index 00000000..3b4798a3--- /dev/null+++ b/packages/core/src/video/stabilization/motion-path.ts@@ -0,0 +1,163 @@+import type { FlowField } from "../frame-interpolation/types";+import type { MotionSample, CorrectionTransform } from "./types";++export function extractDominantMotion(+ flowField: FlowField,+ frameTime: number,+): MotionSample {+ const { width, height, vectors } = flowField;+ const totalBlocks = width * height;++ const dxValues: number[] = [];+ const dyValues: number[] = [];++ for (let i = 0; i < totalBlocks; i++) {+ const dx = vectors[i * 2];+ const dy = vectors[i * 2 + 1];+ if (dx !== 0 || dy !== 0) {+ dxValues.push(dx);+ dyValues.push(dy);+ }+ }++ if (dxValues.length === 0) {+ return { time: frameTime, dx: 0, dy: 0, rotation: 0 };+ }++ dxValues.sort((a, b) => a - b);+ dyValues.sort((a, b) => a - b);++ const medianDx = dxValues[Math.floor(dxValues.length / 2)];+ const medianDy = dyValues[Math.floor(dyValues.length / 2)];++ const rotation = estimateRotation(flowField, medianDx, medianDy);++ return { time: frameTime, dx: medianDx, dy: medianDy, rotation };+}++function estimateRotation(+ flowField: FlowField,+ globalDx: number,+ globalDy: number,+): number {+ const { width, height, vectors } = flowField;+ const centerX = width / 2;+ const centerY = height / 2;++ let rotationSum = 0;+ let count = 0;++ for (let by = 0; by < height; by++) {+ for (let bx = 0; bx < width; bx++) {+ const idx = (by * width + bx) * 2;+ const dx = vectors[idx] - globalDx;+ const dy = vectors[idx + 1] - globalDy;++ const rx = bx - centerX;+ const ry = by - centerY;+ const dist = Math.sqrt(rx * rx + ry * ry);++ if (dist < 2) continue;++ const cross = rx * dy - ry * dx;+ rotationSum += cross / (dist * dist);+ count++;+ }+ }++ if (count === 0) return 0;+ return rotationSum / count;+}++export function accumulateMotionPath(samples: MotionSample[]): {+ cumDx: number[];+ cumDy: number[];+ cumRotation: number[];+} {+ const cumDx: number[] = [0];+ const cumDy: number[] = [0];+ const cumRotation: number[] = [0];++ for (let i = 0; i < samples.length; i++) {+ cumDx.push(cumDx[i] + samples[i].dx);+ cumDy.push(cumDy[i] + samples[i].dy);+ cumRotation.push(cumRotation[i] + samples[i].rotation);+ }++ return { cumDx, cumDy, cumRotation };+}++export function smoothPath(+ values: number[],+ strength: number,+): number[] {+ const radius = Math.max(1, Math.round((strength / 100) * 30));+ const kernel = buildGaussianKernel(radius);+ const smoothed: number[] = new Array(values.length);++ for (let i = 0; i < values.length; i++) {+ let sum = 0;+ let weightSum = 0;++ for (let k = -radius; k <= radius; k++) {+ const idx = Math.min(Math.max(i + k, 0), values.length - 1);+ const weight = kernel[k + radius];+ sum += values[idx] * weight;+ weightSum += weight;+ }++ smoothed[i] = sum / weightSum;+ }++ return smoothed;+}++function buildGaussianKernel(radius: number): number[] {+ const sigma = radius / 3;+ const kernel: number[] = [];++ for (let i = -radius; i <= radius; i++) {+ kernel.push(Math.exp(-(i * i) / (2 * sigma * sigma)));+ }++ return kernel;+}++export function computeCorrections(+ cumDx: number[],+ cumDy: number[],+ cumRotation: number[],+ smoothedDx: number[],+ smoothedDy: number[],+ smoothedRotation: number[],+ cropMode: "auto" | "none",+): CorrectionTransform[] {+ const corrections: CorrectionTransform[] = [];+ let maxDisplacement = 0;++ for (let i = 0; i < cumDx.length; i++) {+ const corrDx = smoothedDx[i] - cumDx[i];+ const corrDy = smoothedDy[i] - cumDy[i];+ const corrRotation = smoothedRotation[i] - cumRotation[i];++ const displacement = Math.sqrt(corrDx * corrDx + corrDy * corrDy);+ maxDisplacement = Math.max(maxDisplacement, displacement);++ corrections.push({+ dx: corrDx,+ dy: corrDy,+ rotation: corrRotation,+ scale: 1,+ });+ }++ if (cropMode === "auto" && maxDisplacement > 0) {+ const scaleFactor = 1 + maxDisplacement * 0.005;+ const clampedScale = Math.min(scaleFactor, 1.15);+ for (const correction of corrections) {+ correction.scale = clampedScale;+ }+ }++ return corrections;+}diff --git a/packages/core/src/video/stabilization/stabilization-engine.ts b/packages/core/src/video/stabilization/stabilization-engine.tsnew file mode 100644index 00000000..d2d0e5c4--- /dev/null+++ b/packages/core/src/video/stabilization/stabilization-engine.ts@@ -0,0 +1,162 @@+import type { StabilizationProfile, CorrectionTransform, StabilizationConfig } from "./types";+import { DEFAULT_STABILIZATION_CONFIG } from "./types";+import { OpticalFlowCPU } from "../frame-interpolation/optical-flow-cpu";+import { INTERPOLATION_QUALITY_PRESETS } from "../frame-interpolation/types";+import {+ extractDominantMotion,+ accumulateMotionPath,+ smoothPath,+ computeCorrections,+} from "./motion-path";++export class StabilizationEngine {+ private profiles: Map<string, StabilizationProfile> = new Map();+ private flowEngine: OpticalFlowCPU;++ constructor() {+ this.flowEngine = new OpticalFlowCPU(INTERPOLATION_QUALITY_PRESETS.medium);+ }++ hasProfile(clipId: string): boolean {+ return this.profiles.has(clipId);+ }++ async analyzeClip(+ clipId: string,+ videoElement: HTMLVideoElement,+ duration: number,+ config: StabilizationConfig = DEFAULT_STABILIZATION_CONFIG,+ onProgress?: (progress: number) => void,+ ): Promise<StabilizationProfile> {+ const fps = 30;+ const interval = config.analysisInterval;+ const frameCount = Math.ceil((duration * fps) / interval);+ const frameInterval = interval / fps;++ const analysisWidth = Math.min(640, videoElement.videoWidth);+ const analysisHeight = Math.round(+ analysisWidth * (videoElement.videoHeight / videoElement.videoWidth),+ );++ const canvas = document.createElement("canvas");+ canvas.width = analysisWidth;+ canvas.height = analysisHeight;+ const ctx = canvas.getContext("2d")!;++ let prevImageData: ImageData | null = null;+ const samples = [];++ for (let i = 0; i <= frameCount; i++) {+ const time = Math.min(i * frameInterval, duration - 0.001);++ videoElement.currentTime = time;+ await new Promise<void>((resolve) => {+ const onSeeked = () => {+ videoElement.removeEventListener("seeked", onSeeked);+ resolve();+ };+ videoElement.addEventListener("seeked", onSeeked);+ setTimeout(resolve, 1000);+ });++ ctx.drawImage(videoElement, 0, 0, analysisWidth, analysisHeight);+ const currentImageData = ctx.getImageData(0, 0, analysisWidth, analysisHeight);++ if (prevImageData) {+ const flowField = await this.flowEngine.computeFlowField(+ prevImageData,+ currentImageData,+ );+ const sample = extractDominantMotion(flowField, time);+ samples.push(sample);+ }++ prevImageData = currentImageData;+ onProgress?.(i / frameCount);+ }++ const { cumDx, cumDy, cumRotation } = accumulateMotionPath(samples);++ const smoothedDx = smoothPath(cumDx, config.strength);+ const smoothedDy = smoothPath(cumDy, config.strength);+ const smoothedRotation = smoothPath(cumRotation, config.strength);++ const corrections = computeCorrections(+ cumDx,+ cumDy,+ cumRotation,+ smoothedDx,+ smoothedDy,+ smoothedRotation,+ config.cropMode,+ );++ let maxDisplacement = 0;+ for (const c of corrections) {+ const d = Math.sqrt(c.dx * c.dx + c.dy * c.dy);+ maxDisplacement = Math.max(maxDisplacement, d);+ }++ const profile: StabilizationProfile = {+ clipId,+ samples,+ corrections,+ maxDisplacement,+ frameInterval,+ duration,+ };++ this.profiles.set(clipId, profile);+ return profile;+ }++ getCorrectionTransform(+ clipId: string,+ sourceTime: number,+ ): CorrectionTransform | null {+ const profile = this.profiles.get(clipId);+ if (!profile || profile.corrections.length === 0) return null;++ const frameIndex = sourceTime / profile.frameInterval;+ const idx = Math.min(+ Math.floor(frameIndex),+ profile.corrections.length - 1,+ );+ const nextIdx = Math.min(idx + 1, profile.corrections.length - 1);+ const frac = frameIndex - idx;++ if (idx === nextIdx) return profile.corrections[idx];++ const curr = profile.corrections[idx];+ const next = profile.corrections[nextIdx];++ return {+ dx: curr.dx + (next.dx - curr.dx) * frac,+ dy: curr.dy + (next.dy - curr.dy) * frac,+ rotation: curr.rotation + (next.rotation - curr.rotation) * frac,+ scale: curr.scale + (next.scale - curr.scale) * frac,+ };+ }++ removeProfile(clipId: string): void {+ this.profiles.delete(clipId);+ }++ dispose(): void {+ this.profiles.clear();+ }+}++let stabilizationEngineInstance: StabilizationEngine | null = null;++export function getStabilizationEngine(): StabilizationEngine {+ if (!stabilizationEngineInstance) {+ stabilizationEngineInstance = new StabilizationEngine();+ }+ return stabilizationEngineInstance;+}++export function disposeStabilizationEngine(): void {+ stabilizationEngineInstance?.dispose();+ stabilizationEngineInstance = null;+}diff --git a/packages/core/src/video/stabilization/types.ts b/packages/core/src/video/stabilization/types.tsnew file mode 100644index 00000000..ac456f75--- /dev/null+++ b/packages/core/src/video/stabilization/types.ts@@ -0,0 +1,34 @@+export interface MotionSample {+ time: number;+ dx: number;+ dy: number;+ rotation: number;+}++export interface CorrectionTransform {+ dx: number;+ dy: number;+ rotation: number;+ scale: number;+}++export interface StabilizationProfile {+ clipId: string;+ samples: MotionSample[];+ corrections: CorrectionTransform[];+ maxDisplacement: number;+ frameInterval: number;+ duration: number;+}++export interface StabilizationConfig {+ strength: number;+ cropMode: "auto" | "none";+ analysisInterval: number;+}++export const DEFAULT_STABILIZATION_CONFIG: StabilizationConfig = {+ strength: 50,+ cropMode: "auto",+ analysisInterval: 2,+};diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.tsindex b7a27f73..011debf6 100644--- a/packages/core/src/video/video-engine.ts+++ b/packages/core/src/video/video-engine.ts@@ -27,6 +27,7 @@ import type {} from "./types";import { getSpeedEngine } from "./speed-engine";import { getFrameInterpolationEngine } from "./frame-interpolation";+import { getStabilizationEngine } from "./stabilization";import {ParallelFrameDecoder,getParallelFrameDecoder,@@ -764,10 +765,33 @@ 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,+ },+ };+ }+ }+this.drawFrameToContext(ctx,processedBitmap,- scaledTransform,+ drawTransform,finalTransform.opacity,width,height,