OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: implement aspect ratio handling for clip rendering and transform fit modes
Augustus Otua60d27630f23
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex a49cac35..b7f84b35 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -189,12 +189,57 @@ const applyStabilizationTransform = () as ClipTransform;};+// The WebGPU renderer maps a layer's texture onto a full-canvas quad, so a+// scale of {1,1} stretches the source to the canvas. Bake the aspect-fit+// ratio into the layer scale so GPU compositing letterboxes ("contain") like+// the Canvas2D path instead of distorting mismatched-aspect clips.+const computeFitScale = (+ fitMode: ClipTransform["fitMode"],+ sourceWidth: number,+ sourceHeight: number,+ canvasWidth: number,+ canvasHeight: number,+): { x: number; y: number } => {+ const mode = !fitMode || fitMode === "none" ? "contain" : fitMode;+ if (+ mode === "stretch" ||+ sourceWidth <= 0 ||+ sourceHeight <= 0 ||+ canvasWidth <= 0 ||+ canvasHeight <= 0+ ) {+ return { x: 1, y: 1 };+ }+ const sourceAspect = sourceWidth / sourceHeight;+ const canvasAspect = canvasWidth / canvasHeight;+ let drawWidth: number;+ let drawHeight: number;+ if (mode === "cover") {+ if (sourceAspect > canvasAspect) {+ drawHeight = canvasHeight;+ drawWidth = canvasHeight * sourceAspect;+ } else {+ drawWidth = canvasWidth;+ drawHeight = canvasWidth / sourceAspect;+ }+ } else {+ if (sourceAspect > canvasAspect) {+ drawWidth = canvasWidth;+ drawHeight = canvasWidth / sourceAspect;+ } else {+ drawHeight = canvasHeight;+ drawWidth = canvasHeight * sourceAspect;+ }+ }+ return { x: drawWidth / canvasWidth, y: drawHeight / canvasHeight };+};+const renderFrameWithGPU = async (renderer: Renderer,frame: ImageBitmap,transform: ClipTransform,- _canvasWidth: number,- _canvasHeight: number,+ canvasWidth: number,+ canvasHeight: number,): Promise<ImageBitmap | null> => {try {const device = renderer.getDevice();@@ -206,9 +251,19 @@ const renderFrameWithGPU = async (const texture = renderer.createTextureFromImage(frame);+ const fitScale = computeFitScale(+ transform.fitMode,+ frame.width,+ frame.height,+ canvasWidth,+ canvasHeight,+ );const gpuTransform = {position: transform.position,- scale: transform.scale,+ scale: {+ x: transform.scale.x * fitScale.x,+ y: transform.scale.y * fitScale.y,+ },rotation: transform.rotation,anchor: transform.anchor,opacity: transform.opacity,@@ -235,8 +290,8 @@ const renderFrameWithGPU = async (const renderAllLayersWithGPU = async (renderer: Renderer,layers: GPULayer[],- _canvasWidth: number,- _canvasHeight: number,+ canvasWidth: number,+ canvasHeight: number,): Promise<ImageBitmap | null> => {try {const device = renderer.getDevice();@@ -255,9 +310,19 @@ const renderAllLayersWithGPU = async (const texture = renderer.createTextureFromImage(layer.bitmap);textures.push(texture);+ const fitScale = computeFitScale(+ layer.transform.fitMode,+ layer.bitmap.width,+ layer.bitmap.height,+ canvasWidth,+ canvasHeight,+ );const gpuTransform = {position: layer.transform.position,- scale: layer.transform.scale,+ scale: {+ x: layer.transform.scale.x * fitScale.x,+ y: layer.transform.scale.y * fitScale.y,+ },rotation: layer.transform.rotation,anchor: layer.transform.anchor,opacity: layer.transform.opacity,@@ -4682,7 +4747,10 @@ export const Preview: React.FC = () => {const displayScale = actualWidth / canvasWidth;- const fitMode = clipTransform.fitMode ?? "contain";+ const fitMode =+ !clipTransform.fitMode || clipTransform.fitMode === "none"+ ? "contain"+ : clipTransform.fitMode;const mediaItem = getMediaItem(clip.mediaId);const mediaWidth = mediaItem?.metadata?.width ?? canvasWidth;const mediaHeight = mediaItem?.metadata?.height ?? canvasHeight;@@ -4690,10 +4758,7 @@ export const Preview: React.FC = () => {let baseWidth: number;let baseHeight: number;- if (fitMode === "none") {- baseWidth = mediaWidth;- baseHeight = mediaHeight;- } else if (fitMode === "stretch") {+ if (fitMode === "stretch") {baseWidth = canvasWidth;baseHeight = canvasHeight;} else if (fitMode === "cover") {diff --git a/apps/web/src/components/editor/inspector/tabs/TransformTab.tsx b/apps/web/src/components/editor/inspector/tabs/TransformTab.tsxindex 64b29d4e..9d45f84a 100644--- a/apps/web/src/components/editor/inspector/tabs/TransformTab.tsx+++ b/apps/web/src/components/editor/inspector/tabs/TransformTab.tsx@@ -134,30 +134,34 @@ export const TransformTab: React.FC<TransformTabProps> = ({<span className="text-[10px] text-text-secondary">Fit Mode</span>- <div className="grid grid-cols-4 gap-1">- {(- ["none", "contain", "cover", "stretch"] as FitMode[]- ).map((mode) => (- <button- key={mode}- onClick={() =>- handleTransformChange({ fitMode: mode })- }- className={`py-1.5 rounded text-[9px] capitalize transition-colors ${- (transform.fitMode || "none") === mode- ? "bg-primary text-white"- : "bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"- }`}- >- {mode === "contain"- ? "Fit"- : mode === "cover"- ? "Fill"- : mode === "none"- ? "Original"- : mode}- </button>- ))}+ <div className="grid grid-cols-3 gap-1">+ {(["contain", "cover", "stretch"] as FitMode[]).map(+ (mode) => {+ const activeMode =+ !transform.fitMode || transform.fitMode === "none"+ ? "contain"+ : transform.fitMode;+ return (+ <button+ key={mode}+ onClick={() =>+ handleTransformChange({ fitMode: mode })+ }+ className={`py-1.5 rounded text-[9px] capitalize transition-colors ${+ activeMode === mode+ ? "bg-primary text-white"+ : "bg-background-tertiary border border-border text-text-secondary hover:text-text-primary"+ }`}+ >+ {mode === "contain"+ ? "Fit"+ : mode === "cover"+ ? "Fill"+ : mode}+ </button>+ );+ },+ )}</div></div>)}diff --git a/apps/web/src/components/editor/preview/canvas-renderers.ts b/apps/web/src/components/editor/preview/canvas-renderers.tsindex 18acc99e..ce54804d 100644--- a/apps/web/src/components/editor/preview/canvas-renderers.ts+++ b/apps/web/src/components/editor/preview/canvas-renderers.ts@@ -1839,15 +1839,17 @@ export const drawFrameWithTransform = (const sourceAspect = sourceWidth / sourceHeight;const canvasAspect = canvasWidth / canvasHeight;- const fitMode = t.fitMode ?? "contain";+ // Treat a missing or "none" fit as "contain" so clips preserve their+ // aspect ratio (letterboxed) instead of being drawn at raw native pixels.+ // Keeps the playing render consistent with the paused/scrub render, which+ // always letterboxes.+ const fitMode =+ !t.fitMode || t.fitMode === "none" ? "contain" : t.fitMode;let drawWidth: number;let drawHeight: number;- if (fitMode === "none") {- drawWidth = sourceWidth;- drawHeight = sourceHeight;- } else if (fitMode === "stretch") {+ if (fitMode === "stretch") {drawWidth = canvasWidth;drawHeight = canvasHeight;} else if (fitMode === "cover") {diff --git a/apps/web/src/components/editor/preview/types.ts b/apps/web/src/components/editor/preview/types.tsindex e7c0da50..d029d10f 100644--- a/apps/web/src/components/editor/preview/types.ts+++ b/apps/web/src/components/editor/preview/types.ts@@ -27,5 +27,5 @@ export const DEFAULT_TRANSFORM: ClipTransform = {opacity: 1,anchor: { x: 0.5, y: 0.5 },borderRadius: 0,- fitMode: "none",+ fitMode: "contain",};diff --git a/apps/web/src/components/editor/timeline/ClipComponent.tsx b/apps/web/src/components/editor/timeline/ClipComponent.tsxindex deba509e..8e6bb2b2 100644--- a/apps/web/src/components/editor/timeline/ClipComponent.tsx+++ b/apps/web/src/components/editor/timeline/ClipComponent.tsx@@ -99,6 +99,8 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({startY: 0,});const clipRef = useRef<HTMLDivElement>(null);+ const moveCommitRafRef = useRef<number | null>(null);+ const pendingCommitRef = useRef<(() => void) | null>(null);// Drag-drop highlight state: "effect" when an effect is hovered over// the clip body, "transition-left" / "transition-right" when a@@ -428,6 +430,13 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({animationFrameId = requestAnimationFrame(scrollLoop);+ const flushPendingCommit = () => {+ moveCommitRafRef.current = null;+ const commit = pendingCommitRef.current;+ pendingCommitRef.current = null;+ commit?.();+ };+const handleMouseMove = (e: MouseEvent) => {mousePositionRef.current.x = e.clientX;mousePositionRef.current.y = e.clientY;@@ -476,18 +485,32 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({setIsInvalidDrop(isOverDifferentTrackType);pendingDropRef.current = { time: snapResult.time, targetTrackId };- onMoveClip(clip.id, snapResult.time, undefined);-- // Move every companion clip in the multi-selection by the same- // delta. Cross-track moves of the primary don't take any- // companions along — that gets too lossy when they live on tracks- // of a different type — but same-track drags stay locked.- if (multiDragSnapshotRef.current.length > 0) {- const deltaTime = snapResult.time - clip.startTime;- for (const snap of multiDragSnapshotRef.current) {- const newStart = Math.max(0, snap.startTime + deltaTime);- onMoveClip(snap.clipId, newStart, undefined);++ // Coalesce store commits to one per animation frame. A fast mouse+ // fires many mousemove events between frames; dispatching moveClip on+ // each one deep-clones the project and re-renders the whole editor+ // dozens of extra times per frame, which is what made sustained+ // dragging lag and eventually exhaust memory. We keep the latest move+ // in a ref and flush it once per frame.+ const moveTime = snapResult.time;+ const baseStartTime = clip.startTime;+ const companions = multiDragSnapshotRef.current;+ pendingCommitRef.current = () => {+ onMoveClip(clip.id, moveTime, undefined);+ // Move every companion clip in the multi-selection by the same+ // delta. Cross-track moves of the primary don't take any+ // companions along — that gets too lossy when they live on tracks+ // of a different type — but same-track drags stay locked.+ if (companions.length > 0) {+ const deltaTime = moveTime - baseStartTime;+ for (const snap of companions) {+ const newStart = Math.max(0, snap.startTime + deltaTime);+ onMoveClip(snap.clipId, newStart, undefined);+ }}+ };+ if (moveCommitRafRef.current === null) {+ moveCommitRafRef.current = requestAnimationFrame(flushPendingCommit);}onSnapIndicator(snapResult.snapped && snapResult.snapPoint ? snapResult.snapPoint.time : null);@@ -505,6 +528,16 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({cancelAnimationFrame(animationFrameId);}+ // Flush any move queued for the next frame so the clip settles at the+ // final dragged position instead of one frame behind.+ if (moveCommitRafRef.current !== null) {+ cancelAnimationFrame(moveCommitRafRef.current);+ moveCommitRafRef.current = null;+ }+ const pendingCommit = pendingCommitRef.current;+ pendingCommitRef.current = null;+ pendingCommit?.();+const { time, targetTrackId } = pendingDropRef.current;if (targetTrackId) {onMoveClip(clip.id, time, targetTrackId);@@ -525,6 +558,10 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({if (animationFrameId !== null) {cancelAnimationFrame(animationFrameId);}+ if (moveCommitRafRef.current !== null) {+ cancelAnimationFrame(moveCommitRafRef.current);+ moveCommitRafRef.current = null;+ }window.removeEventListener("mousemove", handleMouseMove);window.removeEventListener("mouseup", handleMouseUp);closeGroup();diff --git a/packages/core/src/actions/action-executor.ts b/packages/core/src/actions/action-executor.tsindex ec8ed071..0eebf027 100644--- a/packages/core/src/actions/action-executor.ts+++ b/packages/core/src/actions/action-executor.ts@@ -490,7 +490,7 @@ export class ActionExecutor {rotation: 0,anchor: { x: 0.5, y: 0.5 },opacity: 1,- fitMode: "none" as const,+ fitMode: "contain" as const,};const newClip = {id: crypto.randomUUID(),diff --git a/packages/core/src/playback/playback-controller.ts b/packages/core/src/playback/playback-controller.tsindex 229cf6b9..e6cd01d7 100644--- a/packages/core/src/playback/playback-controller.ts+++ b/packages/core/src/playback/playback-controller.ts@@ -154,7 +154,7 @@ export class PlaybackController {this.project = project;this.state = "stopped";this.masterClock.setDuration(project.timeline.duration);- this.clearAudioBuffer();+ this.pruneAudioBuffers(project);}setDisplayCanvas(canvas: HTMLCanvasElement | OffscreenCanvas): void {@@ -445,20 +445,30 @@ export class PlaybackController {};}+ if (this.isRenderingFrame) {+ return {+ frame: null,+ renderTime: 0,+ fromCache: false,+ timedOut: false,+ };+ }+ this.isRenderingFrame = true;+const startTime = performance.now();+ let timeoutId: ReturnType<typeof setTimeout> | null = null;++ const renderPromise = this.videoEngine.renderFrame(this.project, time);try {const timeoutPromise = new Promise<never>((_, reject) => {- setTimeout(() => {+ timeoutId = setTimeout(() => {reject(new Error("Frame render timeout"));}, this.config.frameRenderTimeout);});// Race between render and timeout- const frame = await Promise.race([- this.videoEngine.renderFrame(this.project, time),- timeoutPromise,- ]);+ const frame = await Promise.race([renderPromise, timeoutPromise]);const renderTime = performance.now() - startTime;this.trackFrameRenderTime(renderTime);@@ -480,6 +490,18 @@ export class PlaybackController {const renderTime = performance.now() - startTime;if (error instanceof Error && error.message === "Frame render timeout") {+ // The render is still in flight and the timeout won the race. When+ // the late frame resolves its ImageBitmap would otherwise be orphaned+ // (never assigned to currentFrame, never closed), leaking GPU memory+ // on every dropped scrub frame. Close it when it lands.+ renderPromise+ .then((late) => {+ if (late && late !== this.currentFrame) {+ late.image.close();+ }+ })+ .catch(() => {});+return {frame: null,renderTime,@@ -495,6 +517,11 @@ export class PlaybackController {fromCache: false,timedOut: false,};+ } finally {+ if (timeoutId !== null) {+ clearTimeout(timeoutId);+ }+ this.isRenderingFrame = false;}}@@ -678,6 +705,30 @@ export class PlaybackController {private clearAudioBuffer(): void {this.stopAudioPlayback();this.audioBufferCache.clear();+ this.audioDecodePromises.clear();+ }++ private pruneAudioBuffers(project: Project): void {+ const referenced = new Set<string>();+ for (const track of project.timeline.tracks) {+ if (track.type !== "audio" && track.type !== "video") continue;+ for (const clip of track.clips) {+ referenced.add(clip.mediaId);+ }+ }++ for (const mediaId of [...this.audioBufferCache.keys()]) {+ if (!referenced.has(mediaId)) {+ this.audioBufferCache.delete(mediaId);+ }+ }+ for (const mediaId of [...this.audioDecodePromises.keys()]) {+ if (!referenced.has(mediaId)) {+ this.audioDecodePromises.delete(mediaId);+ }+ }++ this.stopAudioPlayback();}private trackFrameRenderTime(time: number): void {diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.tsindex 9a6dedd6..13f1a783 100644--- a/packages/core/src/video/video-engine.ts+++ b/packages/core/src/video/video-engine.ts@@ -970,32 +970,35 @@ export class VideoEngine {cropDrawHeight,);} else {- const fitMode = transform.fitMode ?? "none";+ // Treat a missing or "none" fit as "contain" so clips preserve their+ // aspect ratio on export/compositing, matching the preview.+ const fitMode =+ !transform.fitMode || transform.fitMode === "none"+ ? "contain"+ : transform.fitMode;let drawWidth = frame.width;let drawHeight = frame.height;- if (fitMode !== "none") {- const sourceAspect = frame.width / frame.height;- const canvasAspect = canvasWidth / canvasHeight;- if (fitMode === "stretch") {- drawWidth = canvasWidth;+ const sourceAspect = frame.width / frame.height;+ const canvasAspect = canvasWidth / canvasHeight;+ if (fitMode === "stretch") {+ drawWidth = canvasWidth;+ drawHeight = canvasHeight;+ } else if (fitMode === "cover") {+ if (sourceAspect > canvasAspect) {drawHeight = canvasHeight;- } else if (fitMode === "cover") {- if (sourceAspect > canvasAspect) {- drawHeight = canvasHeight;- drawWidth = canvasHeight * sourceAspect;- } else {- drawWidth = canvasWidth;- drawHeight = canvasWidth / sourceAspect;- }+ drawWidth = canvasHeight * sourceAspect;} else {- if (sourceAspect > canvasAspect) {- drawWidth = canvasWidth;- drawHeight = canvasWidth / sourceAspect;- } else {- drawHeight = canvasHeight;- drawWidth = canvasHeight * sourceAspect;- }+ drawWidth = canvasWidth;+ drawHeight = canvasWidth / sourceAspect;+ }+ } else {+ if (sourceAspect > canvasAspect) {+ drawWidth = canvasWidth;+ drawHeight = canvasWidth / sourceAspect;+ } else {+ drawHeight = canvasHeight;+ drawWidth = canvasHeight * sourceAspect;}}@@ -2319,32 +2322,35 @@ export class VideoEngine {cropDrawHeight,);} else {- const fitMode = transform.fitMode ?? "none";+ // Treat a missing or "none" fit as "contain" so clips preserve their+ // aspect ratio on export/compositing, matching the preview.+ const fitMode =+ !transform.fitMode || transform.fitMode === "none"+ ? "contain"+ : transform.fitMode;let drawWidth = frame.width;let drawHeight = frame.height;- if (fitMode !== "none") {- const sourceAspect = frame.width / frame.height;- const canvasAspect = canvasWidth / canvasHeight;- if (fitMode === "stretch") {- drawWidth = canvasWidth;+ const sourceAspect = frame.width / frame.height;+ const canvasAspect = canvasWidth / canvasHeight;+ if (fitMode === "stretch") {+ drawWidth = canvasWidth;+ drawHeight = canvasHeight;+ } else if (fitMode === "cover") {+ if (sourceAspect > canvasAspect) {drawHeight = canvasHeight;- } else if (fitMode === "cover") {- if (sourceAspect > canvasAspect) {- drawHeight = canvasHeight;- drawWidth = canvasHeight * sourceAspect;- } else {- drawWidth = canvasWidth;- drawHeight = canvasWidth / sourceAspect;- }+ drawWidth = canvasHeight * sourceAspect;} else {- if (sourceAspect > canvasAspect) {- drawWidth = canvasWidth;- drawHeight = canvasWidth / sourceAspect;- } else {- drawHeight = canvasHeight;- drawWidth = canvasHeight * sourceAspect;- }+ drawWidth = canvasWidth;+ drawHeight = canvasWidth / sourceAspect;+ }+ } else {+ if (sourceAspect > canvasAspect) {+ drawWidth = canvasWidth;+ drawHeight = canvasWidth / sourceAspect;+ } else {+ drawHeight = canvasHeight;+ drawWidth = canvasHeight * sourceAspect;}}