OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: stabilization trim support, export integration, and quality improvements
Augustus Otuee43bbaa0541
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex 0567c2f6..dedb5b4c 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -1373,9 +1373,8 @@ export const Preview: React.FC = () => {clip.id,clipLocalTime,);- const mediaTime = (clip.inPoint || 0) + adjustedLocalTime;-const isStabilized = vidstab.hasStabilized(clip.id);+ const mediaTime = isStabilized ? adjustedLocalTime : (clip.inPoint || 0) + adjustedLocalTime;const cacheKey = isStabilized ? `${clip.mediaId}:stabilized` : clip.mediaId;let cached = videoElementCacheRef.current.get(cacheKey);@@ -2344,11 +2343,15 @@ export const Preview: React.FC = () => {clip: (typeof timelineTracks)[0]["clips"][0],mediaItem: NonNullable<ReturnType<typeof getMediaItem>>,): Promise<void> => {- if (videoCache.has(clip.mediaId)) {+ const vidstabCheck = getVidstabEngine();+ const clipStabilized = vidstabCheck.hasStabilized(clip.id);+ const videoCacheId = clipStabilized ? `stabilized:${clip.id}` : clip.mediaId;++ if (videoCache.has(videoCacheId)) {return Promise.resolve();}- const existingLoad = loadingVideos.get(clip.mediaId);+ const existingLoad = loadingVideos.get(videoCacheId);if (existingLoad) {return existingLoad;}@@ -2358,9 +2361,11 @@ export const Preview: React.FC = () => {}const vidstabEng = getVidstabEngine();- const playBlob = (vidstabEng.hasStabilized(clip.id)+ const isStabilized = vidstabEng.hasStabilized(clip.id);+ const playBlob = (isStabilized? vidstabEng.getStabilizedBlob(clip.id): mediaItem.blob)!;+ const cacheId = isStabilized ? `stabilized:${clip.id}` : clip.mediaId;const url = URL.createObjectURL(playBlob);const video = document.createElement("video");video.src = url;@@ -2368,7 +2373,7 @@ export const Preview: React.FC = () => {video.playsInline = true;video.preload = "metadata";- videoCache.set(clip.mediaId, { video, url });+ videoCache.set(cacheId, { video, url });const loadPromise = new Promise<void>((resolve) => {let settled = false;@@ -2377,7 +2382,7 @@ export const Preview: React.FC = () => {settled = true;video.onloadedmetadata = null;video.onerror = null;- loadingVideos.delete(clip.mediaId);+ loadingVideos.delete(cacheId);resolve();};video.onloadedmetadata = finish;@@ -2385,7 +2390,7 @@ export const Preview: React.FC = () => {setTimeout(finish, 750);});- loadingVideos.set(clip.mediaId, loadPromise);+ loadingVideos.set(cacheId, loadPromise);return loadPromise;};@@ -2588,7 +2593,10 @@ export const Preview: React.FC = () => {}const { clip, mediaItem } = activeClip;- const cached = videoCache.get(clip.mediaId);+ const vidstabPlay = getVidstabEngine();+ const clipIsStabilized = vidstabPlay.hasStabilized(clip.id);+ const playbackCacheId = clipIsStabilized ? `stabilized:${clip.id}` : clip.mediaId;+ const cached = videoCache.get(playbackCacheId);if (!cached) {await loadVideoForClip(clip, mediaItem);@@ -2628,9 +2636,10 @@ export const Preview: React.FC = () => {latestClip.inPoint,Math.min(latestClip.outPoint, latestClip.inPoint + adjustedLocalTime),);- const drift = Math.abs(video.currentTime - sourceTime);+ const videoTime = clipIsStabilized ? sourceTime - latestClip.inPoint : sourceTime;+ const drift = Math.abs(video.currentTime - videoTime);if (drift > 0.1) {- video.currentTime = sourceTime;+ video.currentTime = videoTime;}let transform = getAnimatedTransform(diff --git a/apps/web/src/components/editor/inspector/StabilizationSection.tsx b/apps/web/src/components/editor/inspector/StabilizationSection.tsxindex 94351a09..6574b4e6 100644--- a/apps/web/src/components/editor/inspector/StabilizationSection.tsx+++ b/apps/web/src/components/editor/inspector/StabilizationSection.tsx@@ -16,6 +16,7 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({const [processing, setProcessing] = useState(false);const [stage, setStage] = useState<VidstabProgress["stage"] | null>(null);const [progress, setProgress] = useState(0);+ const [error, setError] = useState<string | null>(null);const stabilization = clip.stabilization ?? {enabled: false,@@ -61,6 +62,7 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({setProcessing(true);setProgress(0);+ setError(null);setStage("downloading");try {@@ -84,11 +86,14 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({setStage(p.stage);setProgress(Math.round(p.progress * 100));},+ { inPoint: clip.inPoint, outPoint: clip.outPoint },);updateStabilization({ enabled: true, analyzed: true });} catch (error) {- console.warn("Stabilization failed:", error);+ console.error("Stabilization failed:", error);+ setStage(null);+ setError(error instanceof Error ? error.message : "Stabilization failed");} finally {setProcessing(false);setStage(null);@@ -197,6 +202,12 @@ export const StabilizationSection: React.FC<StabilizationSectionProps> = ({</div>)}+ {error && !processing && (+ <div className="rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-[11px] text-destructive">+ {error}+ </div>+ )}+{isStabilized && !processing && (<Buttonvariant="outline"diff --git a/packages/core/src/video/stabilization/vidstab-engine.ts b/packages/core/src/video/stabilization/vidstab-engine.tsindex 6ad15a39..16b912df 100644--- a/packages/core/src/video/stabilization/vidstab-engine.ts+++ b/packages/core/src/video/stabilization/vidstab-engine.ts@@ -108,6 +108,7 @@ export class VidstabEngine {sourceBlob: Blob,config: StabilizationConfig = DEFAULT_STABILIZATION_CONFIG,onProgress?: (progress: VidstabProgress) => void,+ trimRange?: { inPoint: number; outPoint: number },): Promise<Blob> {if (!this.ffmpeg || !this.loaded) {throw new Error("VidstabEngine not loaded. Call load() first.");@@ -117,52 +118,110 @@ export class VidstabEngine {await this.ffmpeg.writeFile("input.mp4", inputData);const shakiness = Math.max(1, Math.min(10, Math.round(config.strength / 10)));+ const accuracy = Math.max(3, Math.min(15, Math.round((config.strength / 100) * 15)));const smoothing = Math.max(1, Math.round((config.strength / 100) * 30));const zoom = config.cropMode === "auto" ? -1 : 0;+ const logs: string[] = [];+ let frameCount = 0;+ let totalFrames = 0;+ const logHandler = (data: { message?: string; type?: string }) => {+ if (!data.message) return;+ logs.push(data.message);++ const durationMatch = data.message.match(/Duration:\s*(\d+):(\d+):(\d+)\.(\d+)/);+ if (durationMatch) {+ const secs = parseInt(durationMatch[1]) * 3600 + parseInt(durationMatch[2]) * 60 + parseInt(durationMatch[3]) + parseInt(durationMatch[4]) / 100;+ const fpsMatch = logs.join(" ").match(/(\d+(?:\.\d+)?) fps/);+ const fps = fpsMatch ? parseFloat(fpsMatch[1]) : 30;+ totalFrames = Math.round(secs * fps);+ }++ if (data.message.includes("Discarding frame")) {+ frameCount++;+ if (totalFrames > 0) {+ onProgress?.({ stage: "detecting", progress: frameCount / totalFrames });+ }+ }+ };+ this.ffmpeg.on("log", logHandler);+let progressHandler: ((data: { progress?: number }) => void) | null = null;- progressHandler = (data: { progress?: number }) => {- if (data.progress !== undefined) {- onProgress?.({ stage: "detecting", progress: data.progress });+ progressHandler = (data: { progress?: number; time?: number }) => {+ if (data.progress !== undefined && data.progress > 0) {+ onProgress?.({ stage: "detecting", progress: Math.min(data.progress, 1) });+ } else if (data.time !== undefined && data.time > 0 && totalFrames > 0) {+ const timeSecs = data.time / 1000000;+ const fpsMatch = logs.join(" ").match(/(\d+(?:\.\d+)?) fps/);+ const fps = fpsMatch ? parseFloat(fpsMatch[1]) : 30;+ const durationSecs = totalFrames / fps;+ if (durationSecs > 0) {+ onProgress?.({ stage: "detecting", progress: Math.min(timeSecs / durationSecs, 0.99) });+ }}};this.ffmpeg.on("progress", progressHandler);+ const inputArgs: string[] = [];+ if (trimRange && trimRange.inPoint > 0) {+ inputArgs.push("-ss", trimRange.inPoint.toString());+ }+ inputArgs.push("-i", "input.mp4");+ if (trimRange && trimRange.outPoint > trimRange.inPoint) {+ inputArgs.push("-t", (trimRange.outPoint - trimRange.inPoint).toString());+ }+const detectResult = await this.ffmpeg.exec([- "-i", "input.mp4",- "-vf", `vidstabdetect=shakiness=${shakiness}:accuracy=15:result=transforms.trf`,+ ...inputArgs,+ "-an",+ "-vf", `vidstabdetect=shakiness=${shakiness}:accuracy=${accuracy}:result=transforms.trf`,"-f", "null","-",]);if (detectResult !== 0) {this.ffmpeg.off("progress", progressHandler);+ this.ffmpeg.off("log", logHandler);await this.cleanup();- throw new Error("vidstabdetect failed");+ throw new Error(`vidstabdetect failed: ${logs.slice(-5).join(" | ")}`);}this.ffmpeg.off("progress", progressHandler);- progressHandler = (data: { progress?: number }) => {- if (data.progress !== undefined) {- onProgress?.({ stage: "stabilizing", progress: data.progress });+ onProgress?.({ stage: "stabilizing", progress: 0 });++ progressHandler = (data: { progress?: number; time?: number }) => {+ if (data.progress !== undefined && data.progress > 0) {+ onProgress?.({ stage: "stabilizing", progress: Math.min(data.progress, 1) });+ } else if (data.time !== undefined && data.time > 0 && totalFrames > 0) {+ const timeSecs = data.time / 1000000;+ const fpsMatch = logs.join(" ").match(/(\d+(?:\.\d+)?) fps/);+ const fps = fpsMatch ? parseFloat(fpsMatch[1]) : 30;+ const durationSecs = totalFrames / fps;+ if (durationSecs > 0) {+ onProgress?.({ stage: "stabilizing", progress: Math.min(timeSecs / durationSecs, 0.99) });+ }}};this.ffmpeg.on("progress", progressHandler);const transformResult = await this.ffmpeg.exec([- "-i", "input.mp4",+ ...inputArgs,"-vf", `vidstabtransform=input=transforms.trf:smoothing=${smoothing}:zoom=${zoom}:interpol=bicubic`,+ "-preset", "slow",+ "-crf", "15","-c:a", "copy","output.mp4",]);this.ffmpeg.off("progress", progressHandler);+ this.ffmpeg.off("log", logHandler);+if (transformResult !== 0) {await this.cleanup();- throw new Error("vidstabtransform failed");+ throw new Error(`vidstabtransform failed: ${logs.slice(-5).join(" | ")}`);}const outputData = await this.ffmpeg.readFile("output.mp4");diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.tsindex 73b85565..7ece3644 100644--- a/packages/core/src/video/video-engine.ts+++ b/packages/core/src/video/video-engine.ts@@ -645,19 +645,37 @@ export class VideoEngine {}if (!bitmap) {+ const vidstabForDecode = getVidstabEngine();+ const useStabilizedBlob = vidstabForDecode.hasStabilized(clip.id);+ const decodeBlob = useStabilizedBlob+ ? vidstabForDecode.getStabilizedBlob(clip.id)!+ : mediaItem.blob;+ const decodeTime = useStabilizedBlob+ ? clipInfo.sourceTime - clip.inPoint+ : clipInfo.sourceTime;+bitmap = await this.decodeFrameWithMediaBunny(- mediaItem.blob,- clipInfo.sourceTime,+ decodeBlob,+ decodeTime,settings.width,settings.height,- clipInfo.mediaId,+ useStabilizedBlob ? `stabilized:${clip.id}` : clipInfo.mediaId,);}if (!bitmap) {+ const vidstabForDecode = getVidstabEngine();+ const useStabilizedBlob = vidstabForDecode.hasStabilized(clip.id);+ const decodeBlob = useStabilizedBlob+ ? vidstabForDecode.getStabilizedBlob(clip.id)!+ : mediaItem.blob;+ const decodeTime = useStabilizedBlob+ ? clipInfo.sourceTime - clip.inPoint+ : clipInfo.sourceTime;+bitmap = await this.decodeFrameWithVideoElement(- mediaItem.id,- mediaItem.blob,- clipInfo.sourceTime,+ useStabilizedBlob ? `stabilized:${clip.id}` : mediaItem.id,+ decodeBlob,+ decodeTime,settings.width,settings.height,);