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: host vidstab WASM on R2 and improve stabilization engine

Augustus Otu1050b09afe37
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index c633e463..dc18339f 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -1,5 +1,6 @@
import type { TransitionType } from "./effects";
import type { EmphasisAnimation } from "../graphics/types";
+import type { StabilizationProfile } from "../video/stabilization/types";
export interface Timeline {
readonly tracks: Track[];
@@ -65,6 +66,8 @@ export interface Clip {
strength: number;
cropMode: "auto" | "none";
analyzed?: boolean;
+ analysisVersion?: number;
+ profile?: StabilizationProfile;
};
readonly emphasisAnimation?: EmphasisAnimation;
/** Zero-based index of the audio track within the source media file to use for this clip.
diff --git a/packages/core/src/video/stabilization/motion-path.ts b/packages/core/src/video/stabilization/motion-path.ts
index 3b4798a3..0c766e17 100644
--- a/packages/core/src/video/stabilization/motion-path.ts
+++ b/packages/core/src/video/stabilization/motion-path.ts
@@ -7,66 +7,121 @@ export function extractDominantMotion(
): MotionSample {
const { width, height, vectors } = flowField;
const totalBlocks = width * height;
-
- const dxValues: number[] = [];
- const dyValues: number[] = [];
+ const motionVectors: Array<{ dx: number; dy: number; magnitude: 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);
+ motionVectors.push({
+ dx,
+ dy,
+ magnitude: Math.hypot(dx, dy),
+ });
}
}
- if (dxValues.length === 0) {
+ if (motionVectors.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 };
+ const dominantMotion = findDominantMotionCluster(motionVectors);
+ return {
+ time: frameTime,
+ dx: dominantMotion.dx,
+ dy: dominantMotion.dy,
+ rotation: 0,
+ };
}
-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;
+function findDominantMotionCluster(
+ motionVectors: Array<{ dx: number; dy: number; magnitude: number }>,
+): { dx: number; dy: number } {
+ const bins = new Map<
+ string,
+ {
+ qdx: number;
+ qdy: number;
+ totalDx: number;
+ totalDy: number;
+ totalMagnitude: number;
+ count: number;
+ }
+ >();
+
+ for (const vector of motionVectors) {
+ const qdx = Math.round(vector.dx);
+ const qdy = Math.round(vector.dy);
+ const key = `${qdx},${qdy}`;
+ const bin = bins.get(key) ?? {
+ qdx,
+ qdy,
+ totalDx: 0,
+ totalDy: 0,
+ totalMagnitude: 0,
+ count: 0,
+ };
+
+ bin.totalDx += vector.dx;
+ bin.totalDy += vector.dy;
+ bin.totalMagnitude += vector.magnitude;
+ bin.count += 1;
+ bins.set(key, bin);
+ }
- const rx = bx - centerX;
- const ry = by - centerY;
- const dist = Math.sqrt(rx * rx + ry * ry);
+ let bestBin:
+ | {
+ qdx: number;
+ qdy: number;
+ totalDx: number;
+ totalDy: number;
+ totalMagnitude: number;
+ count: number;
+ }
+ | undefined;
+
+ for (const bin of bins.values()) {
+ if (
+ !bestBin ||
+ bin.count > bestBin.count ||
+ (bin.count === bestBin.count &&
+ bin.totalMagnitude > bestBin.totalMagnitude)
+ ) {
+ bestBin = bin;
+ }
+ }
- if (dist < 2) continue;
+ if (!bestBin) {
+ return { dx: 0, dy: 0 };
+ }
- const cross = rx * dy - ry * dx;
- rotationSum += cross / (dist * dist);
- count++;
+ let clusteredDx = 0;
+ let clusteredDy = 0;
+ let clusteredWeight = 0;
+
+ for (const vector of motionVectors) {
+ if (
+ Math.abs(vector.dx - bestBin.qdx) <= 1 &&
+ Math.abs(vector.dy - bestBin.qdy) <= 1
+ ) {
+ const weight = Math.max(vector.magnitude, 1);
+ clusteredDx += vector.dx * weight;
+ clusteredDy += vector.dy * weight;
+ clusteredWeight += weight;
}
}
- if (count === 0) return 0;
- return rotationSum / count;
+ if (clusteredWeight === 0) {
+ return {
+ dx: bestBin.totalDx / bestBin.count,
+ dy: bestBin.totalDy / bestBin.count,
+ };
+ }
+
+ return {
+ dx: clusteredDx / clusteredWeight,
+ dy: clusteredDy / clusteredWeight,
+ };
}
export function accumulateMotionPath(samples: MotionSample[]): {
@@ -91,7 +146,15 @@ export function smoothPath(
values: number[],
strength: number,
): number[] {
- const radius = Math.max(1, Math.round((strength / 100) * 30));
+ if (values.length <= 1) {
+ return [...values];
+ }
+
+ const maxRadius = Math.max(1, Math.floor((values.length - 1) / 2));
+ const radius = Math.min(
+ maxRadius,
+ Math.max(1, Math.round((strength / 100) * 60)),
+ );
const kernel = buildGaussianKernel(radius);
const smoothed: number[] = new Array(values.length);
@@ -131,17 +194,20 @@ export function computeCorrections(
smoothedDy: number[],
smoothedRotation: number[],
cropMode: "auto" | "none",
+ analysisWidth: number,
+ analysisHeight: number,
): CorrectionTransform[] {
const corrections: CorrectionTransform[] = [];
- let maxDisplacement = 0;
+ let maxAbsDx = 0;
+ let maxAbsDy = 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);
+ maxAbsDx = Math.max(maxAbsDx, Math.abs(corrDx));
+ maxAbsDy = Math.max(maxAbsDy, Math.abs(corrDy));
corrections.push({
dx: corrDx,
@@ -151,8 +217,13 @@ export function computeCorrections(
});
}
- if (cropMode === "auto" && maxDisplacement > 0) {
- const scaleFactor = 1 + maxDisplacement * 0.005;
+ if (cropMode === "auto" && (maxAbsDx > 0 || maxAbsDy > 0)) {
+ const safeWidth = Math.max(analysisWidth - maxAbsDx * 2, 1);
+ const safeHeight = Math.max(analysisHeight - maxAbsDy * 2, 1);
+ const scaleFactor = Math.max(
+ analysisWidth / safeWidth,
+ analysisHeight / safeHeight,
+ );
const clampedScale = Math.min(scaleFactor, 1.15);
for (const correction of corrections) {
correction.scale = clampedScale;
diff --git a/packages/core/src/video/stabilization/stabilization-engine.ts b/packages/core/src/video/stabilization/stabilization-engine.ts
index d2d0e5c4..1c467908 100644
--- a/packages/core/src/video/stabilization/stabilization-engine.ts
+++ b/packages/core/src/video/stabilization/stabilization-engine.ts
@@ -1,5 +1,14 @@
-import type { StabilizationProfile, CorrectionTransform, StabilizationConfig } from "./types";
-import { DEFAULT_STABILIZATION_CONFIG } from "./types";
+import type {
+ StabilizationProfile,
+ CorrectionTransform,
+ StabilizationConfig,
+ StabilizationRenderContext,
+} from "./types";
+import type { Clip, Transform } from "../../types/timeline";
+import {
+ DEFAULT_STABILIZATION_CONFIG,
+ STABILIZATION_ANALYSIS_VERSION,
+} from "./types";
import { OpticalFlowCPU } from "../frame-interpolation/optical-flow-cpu";
import { INTERPOLATION_QUALITY_PRESETS } from "../frame-interpolation/types";
import {
@@ -14,26 +23,44 @@ export class StabilizationEngine {
private flowEngine: OpticalFlowCPU;
constructor() {
- this.flowEngine = new OpticalFlowCPU(INTERPOLATION_QUALITY_PRESETS.medium);
+ this.flowEngine = new OpticalFlowCPU(INTERPOLATION_QUALITY_PRESETS.high);
}
hasProfile(clipId: string): boolean {
return this.profiles.has(clipId);
}
+ setProfile(profile: StabilizationProfile): void {
+ this.profiles.set(profile.clipId, profile);
+ }
+
async analyzeClip(
clipId: string,
videoElement: HTMLVideoElement,
duration: number,
+ sourceStartTime: number = 0,
config: StabilizationConfig = DEFAULT_STABILIZATION_CONFIG,
onProgress?: (progress: number) => void,
): Promise<StabilizationProfile> {
+ if (!Number.isFinite(duration) || duration <= 0) {
+ throw new Error("Stabilization analysis requires a positive duration");
+ }
+
+ if (!Number.isFinite(sourceStartTime) || sourceStartTime < 0) {
+ throw new Error("Stabilization analysis requires a valid source start time");
+ }
+
+ if (videoElement.videoWidth <= 0 || videoElement.videoHeight <= 0) {
+ throw new Error("Stabilization analysis requires loaded video metadata");
+ }
+
const fps = 30;
- const interval = config.analysisInterval;
- const frameCount = Math.ceil((duration * fps) / interval);
+ const interval = Math.max(1, config.analysisInterval);
+ const frameCount = Math.max(1, Math.ceil((duration * fps) / interval));
const frameInterval = interval / fps;
+ const maxRelativeTime = Math.max(duration - 0.001, 0);
- const analysisWidth = Math.min(640, videoElement.videoWidth);
+ const analysisWidth = Math.min(960, videoElement.videoWidth);
const analysisHeight = Math.round(
analysisWidth * (videoElement.videoHeight / videoElement.videoWidth),
);
@@ -45,19 +72,16 @@ export class StabilizationEngine {
let prevImageData: ImageData | null = null;
const samples = [];
+ const maxSourceTime = Number.isFinite(videoElement.duration)
+ ? Math.max(videoElement.duration - 0.001, 0)
+ : sourceStartTime + maxRelativeTime;
+ const maxMotionPerSample = Math.max(12, analysisWidth * 0.03);
for (let i = 0; i <= frameCount; i++) {
- const time = Math.min(i * frameInterval, duration - 0.001);
+ const relativeTime = Math.min(i * frameInterval, maxRelativeTime);
+ const sourceTime = Math.min(sourceStartTime + relativeTime, maxSourceTime);
- videoElement.currentTime = time;
- await new Promise<void>((resolve) => {
- const onSeeked = () => {
- videoElement.removeEventListener("seeked", onSeeked);
- resolve();
- };
- videoElement.addEventListener("seeked", onSeeked);
- setTimeout(resolve, 1000);
- });
+ await this.seekVideoFrame(videoElement, sourceTime);
ctx.drawImage(videoElement, 0, 0, analysisWidth, analysisHeight);
const currentImageData = ctx.getImageData(0, 0, analysisWidth, analysisHeight);
@@ -67,7 +91,10 @@ export class StabilizationEngine {
prevImageData,
currentImageData,
);
- const sample = extractDominantMotion(flowField, time);
+ const sample = this.clampMotionSample(
+ extractDominantMotion(flowField, sourceTime),
+ maxMotionPerSample,
+ );
samples.push(sample);
}
@@ -89,6 +116,8 @@ export class StabilizationEngine {
smoothedDy,
smoothedRotation,
config.cropMode,
+ analysisWidth,
+ analysisHeight,
);
let maxDisplacement = 0;
@@ -104,20 +133,126 @@ export class StabilizationEngine {
maxDisplacement,
frameInterval,
duration,
+ sourceStartTime,
+ analysisDimensions: {
+ width: analysisWidth,
+ height: analysisHeight,
+ },
};
this.profiles.set(clipId, profile);
return profile;
}
+ private clampMotionSample(
+ sample: StabilizationProfile["samples"][number],
+ maxMotionPerSample: number,
+ ): StabilizationProfile["samples"][number] {
+ const magnitude = Math.hypot(sample.dx, sample.dy);
+ if (magnitude <= maxMotionPerSample || magnitude === 0) {
+ return sample;
+ }
+
+ const scale = maxMotionPerSample / magnitude;
+ return {
+ ...sample,
+ dx: sample.dx * scale,
+ dy: sample.dy * scale,
+ };
+ }
+
+ private async seekVideoFrame(
+ videoElement: HTMLVideoElement,
+ sourceTime: number,
+ ): Promise<void> {
+ const maxSourceTime = Number.isFinite(videoElement.duration)
+ ? Math.max(videoElement.duration - 0.001, 0)
+ : Math.max(sourceTime, 0);
+ const clampedTime = Math.max(0, Math.min(sourceTime, maxSourceTime));
+ const seekTime =
+ clampedTime <= 0 && maxSourceTime > 0.002 ? 0.001 : clampedTime;
+ const needsSeek =
+ Math.abs(videoElement.currentTime - seekTime) > 0.01 ||
+ videoElement.readyState < HTMLMediaElement.HAVE_CURRENT_DATA;
+
+ if (needsSeek) {
+ await new Promise<void>((resolve) => {
+ let settled = false;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ if (timeoutId) {
+ window.clearTimeout(timeoutId);
+ }
+ videoElement.removeEventListener("seeked", onSeeked);
+ resolve();
+ };
+ const onSeeked = () => {
+ finish();
+ };
+ const timeoutId = window.setTimeout(finish, 3000);
+
+ videoElement.addEventListener("seeked", onSeeked);
+ videoElement.currentTime = seekTime;
+ });
+ }
+
+ await this.waitForRenderableFrame(videoElement);
+ }
+
+ private async waitForRenderableFrame(
+ videoElement: HTMLVideoElement,
+ ): Promise<void> {
+ await new Promise<void>((resolve) => {
+ let settled = false;
+ let callbackId: number | null = null;
+
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ if (timeoutId) {
+ window.clearTimeout(timeoutId);
+ }
+ if (
+ callbackId !== null &&
+ typeof videoElement.cancelVideoFrameCallback === "function"
+ ) {
+ videoElement.cancelVideoFrameCallback(callbackId);
+ }
+ resolve();
+ };
+
+ const timeoutId = window.setTimeout(finish, 250);
+
+ if (typeof videoElement.requestVideoFrameCallback === "function") {
+ callbackId = videoElement.requestVideoFrameCallback(() => {
+ finish();
+ });
+ return;
+ }
+
+ window.requestAnimationFrame(() => {
+ window.requestAnimationFrame(() => {
+ finish();
+ });
+ });
+ });
+ }
+
getCorrectionTransform(
clipId: string,
sourceTime: number,
+ renderContext?: StabilizationRenderContext,
): CorrectionTransform | null {
const profile = this.profiles.get(clipId);
if (!profile || profile.corrections.length === 0) return null;
- const frameIndex = sourceTime / profile.frameInterval;
+ const relativeSourceTime = Math.max(
+ 0,
+ Math.min(sourceTime - profile.sourceStartTime, profile.duration),
+ );
+
+ const frameIndex = relativeSourceTime / profile.frameInterval;
const idx = Math.min(
Math.floor(frameIndex),
profile.corrections.length - 1,
@@ -125,16 +260,39 @@ export class StabilizationEngine {
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 {
+ const interpolated = idx === nextIdx
+ ? curr
+ : {
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,
+ };
+
+ if (!renderContext) {
+ return interpolated;
+ }
+
+ if (renderContext.sourceWidth <= 0 || renderContext.sourceHeight <= 0) {
+ return interpolated;
+ }
+
+ const fitScale = Math.min(
+ renderContext.canvasWidth / renderContext.sourceWidth,
+ renderContext.canvasHeight / renderContext.sourceHeight,
+ );
+ const renderScaleX =
+ (renderContext.sourceWidth / profile.analysisDimensions.width) * fitScale;
+ const renderScaleY =
+ (renderContext.sourceHeight / profile.analysisDimensions.height) * fitScale;
+
+ return {
+ ...interpolated,
+ dx: interpolated.dx * renderScaleX,
+ dy: interpolated.dy * renderScaleY,
};
}
@@ -147,6 +305,48 @@ export class StabilizationEngine {
}
}
+export function getStabilizedTransform(
+ clip: Clip,
+ transform: Transform,
+ sourceTime: number,
+ renderContext: StabilizationRenderContext,
+): Transform {
+ if (
+ !clip.stabilization?.enabled ||
+ !clip.stabilization.analyzed ||
+ clip.stabilization.analysisVersion !== STABILIZATION_ANALYSIS_VERSION
+ ) {
+ return transform;
+ }
+
+ const engine = getStabilizationEngine();
+ if (!engine.hasProfile(clip.id) && clip.stabilization.profile) {
+ engine.setProfile(clip.stabilization.profile);
+ }
+
+ const correction = engine.getCorrectionTransform(
+ clip.id,
+ sourceTime,
+ renderContext,
+ );
+ if (!correction) {
+ return transform;
+ }
+
+ return {
+ ...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,
+ },
+ };
+}
+
let stabilizationEngineInstance: StabilizationEngine | null = null;
export function getStabilizationEngine(): StabilizationEngine {
diff --git a/packages/core/src/video/stabilization/types.ts b/packages/core/src/video/stabilization/types.ts
index ac456f75..cab96a33 100644
--- a/packages/core/src/video/stabilization/types.ts
+++ b/packages/core/src/video/stabilization/types.ts
@@ -12,6 +12,13 @@ export interface CorrectionTransform {
scale: number;
}
+export interface StabilizationRenderContext {
+ canvasWidth: number;
+ canvasHeight: number;
+ sourceWidth: number;
+ sourceHeight: number;
+}
+
export interface StabilizationProfile {
clipId: string;
samples: MotionSample[];
@@ -19,6 +26,11 @@ export interface StabilizationProfile {
maxDisplacement: number;
frameInterval: number;
duration: number;
+ sourceStartTime: number;
+ analysisDimensions: {
+ width: number;
+ height: number;
+ };
}
export interface StabilizationConfig {
@@ -27,6 +39,8 @@ export interface StabilizationConfig {
analysisInterval: number;
}
+export const STABILIZATION_ANALYSIS_VERSION = 3;
+
export const DEFAULT_STABILIZATION_CONFIG: StabilizationConfig = {
strength: 50,
cropMode: "auto",
diff --git a/packages/core/src/video/stabilization/vidstab-engine.ts b/packages/core/src/video/stabilization/vidstab-engine.ts
index 6d9faaf4..6ad15a39 100644
--- a/packages/core/src/video/stabilization/vidstab-engine.ts
+++ b/packages/core/src/video/stabilization/vidstab-engine.ts
@@ -23,8 +23,8 @@ type FFmpegInstance = {
};
const VIDSTAB_CORE_CDN = {
- mt: "https://unpkg.com/@willyjl/[email protected]/dist/esm",
- st: "https://unpkg.com/@willyjl/[email protected]/dist/esm",
+ mt: "https://mediashares.openreel.video/ffmpeg-vidstab/mt",
+ st: "https://mediashares.openreel.video/ffmpeg-vidstab/st",
};
export type VidstabProgress = {