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: Introduce SpeedEngine for variable speed and reverse playback, separating media and playhead time in the preview, and add comprehensive tests for speed calculations.

Augustus Otud75c8330e55b
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 6622d11f..69dae614 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -79,8 +79,8 @@ 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();
@@ -93,10 +93,7 @@ const renderFrameWithGPU = async (
const texture = renderer.createTextureFromImage(frame);
const gpuTransform = {
- position: {
- x: transform.position.x * canvasWidth,
- y: transform.position.y * canvasHeight,
- },
+ position: transform.position,
scale: transform.scale,
rotation: transform.rotation,
anchor: transform.anchor,
@@ -124,8 +121,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();
@@ -145,10 +142,7 @@ const renderAllLayersWithGPU = async (
textures.push(texture);
const gpuTransform = {
- position: {
- x: layer.transform.position.x * canvasWidth,
- y: layer.transform.position.y * canvasHeight,
- },
+ position: layer.transform.position,
scale: layer.transform.scale,
rotation: layer.transform.rotation,
anchor: layer.transform.anchor,
@@ -2284,7 +2278,10 @@ export const Preview: React.FC = () => {
const frameDuration = 1000 / 30;
// Playback state
+ // currentMediaTime: time in the source video (advances at speed rate)
+ // currentPlayheadTime: time in the timeline (advances at normal rate)
let currentMediaTime = mediaStartTime;
+ let currentPlayheadTime = timelinePosition;
let lastFrameTimestamp = performance.now();
let frameCount = 0;
@@ -2334,8 +2331,10 @@ export const Preview: React.FC = () => {
if (!frameResult || !frameResult.canvas) {
console.warn("[Preview] No frame at time", currentMediaTime);
- // Skip to next frame time
- currentMediaTime += frameDuration / 1000;
+ // Skip to next frame - advance both times keeping them in sync
+ const skipTime = frameDuration / 1000;
+ currentPlayheadTime += skipTime;
+ currentMediaTime += skipTime * currentSpeed;
if (isActive) {
animationRef.current =
requestAnimationFrame(processNextFrame);
@@ -2351,7 +2350,9 @@ export const Preview: React.FC = () => {
"height" in frameCanvas ? frameCanvas.height : 0;
if (frameWidth === 0 || frameHeight === 0) {
console.warn("[Preview] Frame has zero dimensions, skipping");
- currentMediaTime += frameDuration / 1000;
+ const skipTime = frameDuration / 1000;
+ currentPlayheadTime += skipTime;
+ currentMediaTime += skipTime * currentSpeed;
if (isActive) {
animationRef.current =
requestAnimationFrame(processNextFrame);
@@ -2359,9 +2360,7 @@ export const Preview: React.FC = () => {
return;
}
- // Calculate current playhead position
- const currentPlayhead =
- clip.startTime + (currentMediaTime - (clip.inPoint || 0));
+ const currentPlayhead = currentPlayheadTime;
if (currentPlayhead >= actualEndTime) {
setPlayheadPosition(0);
@@ -2471,10 +2470,13 @@ export const Preview: React.FC = () => {
duration > 0 ? duration * 1000 : frameDuration;
const targetTime = actualFrameDuration / rateRef.current;
- // Advance media time based on frame duration and effective clip speed
- // (currentSpeed already includes linked audio clip speed from earlier calculation)
- const timeAdvance = (actualFrameDuration / 1000) * currentSpeed;
- currentMediaTime += timeAdvance;
+ // Advance times:
+ // - playhead advances at normal rate (1x)
+ // - media time advances at speed rate (for fetching correct video frames)
+ const normalTimeAdvance = actualFrameDuration / 1000;
+ const mediaTimeAdvance = normalTimeAdvance * currentSpeed;
+ currentPlayheadTime += normalTimeAdvance;
+ currentMediaTime += mediaTimeAdvance;
const delay = Math.max(0, targetTime - elapsed);
lastFrameTimestamp = now;
@@ -3030,16 +3032,9 @@ export const Preview: React.FC = () => {
);
for (const { transform, frame } of trackFrames) {
if (frame instanceof ImageBitmap) {
- const normalizedTransform = {
- ...transform,
- position: {
- x: 0.5 + transform.position.x / canvas.width,
- y: 0.5 + transform.position.y / canvas.height,
- },
- };
gpuLayers.push({
bitmap: frame,
- transform: normalizedTransform,
+ transform,
});
}
}
diff --git a/apps/web/src/components/editor/preview/canvas-renderers.test.ts b/apps/web/src/components/editor/preview/canvas-renderers.test.ts
new file mode 100644
index 00000000..830af30a
--- /dev/null
+++ b/apps/web/src/components/editor/preview/canvas-renderers.test.ts
@@ -0,0 +1,186 @@
+import { describe, it, expect } from "vitest";
+import { getAnimatedTransform } from "./canvas-renderers";
+import { DEFAULT_TRANSFORM, type ClipTransform } from "./types";
+import type { Keyframe } from "@openreel/core";
+
+describe("getAnimatedTransform", () => {
+ const baseTransform: ClipTransform = {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ opacity: 1,
+ anchor: { x: 0.5, y: 0.5 },
+ borderRadius: 0,
+ };
+
+ it("should return base transform when no keyframes", () => {
+ const result = getAnimatedTransform(baseTransform, [], 0);
+ expect(result).toEqual(baseTransform);
+ });
+
+ it("should return base transform when keyframes is undefined", () => {
+ const result = getAnimatedTransform(baseTransform, undefined, 0);
+ expect(result).toEqual(baseTransform);
+ });
+
+ it("should interpolate position keyframes", () => {
+ const keyframes: Keyframe[] = [
+ { id: "1", property: "position.x", time: 0, value: 0, easing: "linear" },
+ { id: "2", property: "position.x", time: 1, value: 100, easing: "linear" },
+ ];
+
+ const result = getAnimatedTransform(baseTransform, keyframes, 0.5);
+ expect(result.position.x).toBeCloseTo(50, 1);
+ });
+
+ it("should preserve transform position at time 0", () => {
+ const customTransform: ClipTransform = {
+ ...baseTransform,
+ position: { x: 100, y: 50 },
+ };
+
+ const result = getAnimatedTransform(customTransform, [], 0);
+ expect(result.position.x).toBe(100);
+ expect(result.position.y).toBe(50);
+ });
+
+ it("should preserve transform position regardless of clipLocalTime when no keyframes", () => {
+ const customTransform: ClipTransform = {
+ ...baseTransform,
+ position: { x: 200, y: 150 },
+ };
+
+ const times = [0, 0.5, 1, 2, 5, 10];
+ for (const time of times) {
+ const result = getAnimatedTransform(customTransform, [], time);
+ expect(result.position.x).toBe(200);
+ expect(result.position.y).toBe(150);
+ }
+ });
+});
+
+describe("Transform Coordinate System", () => {
+ it("DEFAULT_TRANSFORM position should be at center (0, 0)", () => {
+ expect(DEFAULT_TRANSFORM.position.x).toBe(0);
+ expect(DEFAULT_TRANSFORM.position.y).toBe(0);
+ });
+
+ it("DEFAULT_TRANSFORM anchor should be centered (0.5, 0.5)", () => {
+ expect(DEFAULT_TRANSFORM.anchor.x).toBe(0.5);
+ expect(DEFAULT_TRANSFORM.anchor.y).toBe(0.5);
+ });
+
+ describe("Position coordinates should be in pixels (offset from center)", () => {
+ it("position (0, 0) should represent center of canvas", () => {
+ const transform = { ...DEFAULT_TRANSFORM, position: { x: 0, y: 0 } };
+ expect(transform.position.x).toBe(0);
+ expect(transform.position.y).toBe(0);
+ });
+
+ it("position (100, 0) should represent 100px right of center", () => {
+ const transform = { ...DEFAULT_TRANSFORM, position: { x: 100, y: 0 } };
+ expect(transform.position.x).toBe(100);
+ });
+
+ it("position (-100, 0) should represent 100px left of center", () => {
+ const transform = { ...DEFAULT_TRANSFORM, position: { x: -100, y: 0 } };
+ expect(transform.position.x).toBe(-100);
+ });
+ });
+});
+
+describe("GPU Transform Normalization", () => {
+ it("should NOT add 0.5 offset to normalized coordinates", () => {
+ const canvasWidth = 1920;
+ const canvasHeight = 1080;
+ const position = { x: 0, y: 0 };
+
+ const incorrectNormalization = {
+ x: 0.5 + position.x / canvasWidth,
+ y: 0.5 + position.y / canvasHeight,
+ };
+
+ const correctPassthrough = position;
+
+ expect(incorrectNormalization.x).toBe(0.5);
+ expect(incorrectNormalization.y).toBe(0.5);
+
+ expect(correctPassthrough.x).toBe(0);
+ expect(correctPassthrough.y).toBe(0);
+
+ expect(correctPassthrough.x).not.toBe(incorrectNormalization.x);
+ });
+
+ it("GPU expects pixel coordinates that it normalizes internally", () => {
+ const canvasWidth = 1920;
+ const canvasHeight = 1080;
+
+ const simulateShaderNormalization = (pixelX: number, pixelY: number) => ({
+ x: (pixelX / canvasWidth) * 2,
+ y: (pixelY / canvasHeight) * 2,
+ });
+
+ const center = simulateShaderNormalization(0, 0);
+ expect(center.x).toBe(0);
+ expect(center.y).toBe(0);
+
+ const halfRight = simulateShaderNormalization(canvasWidth / 2, 0);
+ expect(halfRight.x).toBe(1);
+ expect(halfRight.y).toBe(0);
+
+ const topRight = simulateShaderNormalization(canvasWidth / 2, canvasHeight / 2);
+ expect(topRight.x).toBe(1);
+ expect(topRight.y).toBe(1);
+ });
+});
+
+describe("Playback Transform Consistency", () => {
+ it("transform should be identical during playback regardless of speed", () => {
+ const clipTransform: ClipTransform = {
+ position: { x: 100, y: -50 },
+ scale: { x: 1.5, y: 1.5 },
+ rotation: 45,
+ opacity: 0.8,
+ anchor: { x: 0.5, y: 0.5 },
+ borderRadius: 10,
+ };
+
+ const speed1xTransform = getAnimatedTransform(clipTransform, [], 2.5);
+ const speed2xTransform = getAnimatedTransform(clipTransform, [], 2.5);
+
+ expect(speed1xTransform).toEqual(speed2xTransform);
+ expect(speed1xTransform.position).toEqual(clipTransform.position);
+ });
+
+ it("clipLocalTime for transforms should be based on timeline time, not media time", () => {
+ const clipStartTime = 10;
+ const speed = 2;
+
+ const simulateCorrectClipLocalTime = (
+ currentPlayheadTime: number,
+ _speed: number
+ ) => {
+ return currentPlayheadTime - clipStartTime;
+ };
+
+ const simulateIncorrectClipLocalTime = (
+ currentMediaTime: number,
+ inPoint: number,
+ _clipStartTime: number
+ ) => {
+ const currentPlayhead = _clipStartTime + (currentMediaTime - inPoint);
+ return currentPlayhead - _clipStartTime;
+ };
+
+ const realTimeElapsed = 1;
+ const playheadTime = clipStartTime + realTimeElapsed;
+ const mediaTime = realTimeElapsed * speed;
+
+ const correctClipLocalTime = simulateCorrectClipLocalTime(playheadTime, speed);
+ const incorrectClipLocalTime = simulateIncorrectClipLocalTime(mediaTime, 0, clipStartTime);
+
+ expect(correctClipLocalTime).toBe(1);
+ expect(incorrectClipLocalTime).toBe(2);
+ expect(correctClipLocalTime).not.toBe(incorrectClipLocalTime);
+ });
+});
diff --git a/packages/core/src/video/speed-engine.test.ts b/packages/core/src/video/speed-engine.test.ts
new file mode 100644
index 00000000..8cc6fdb5
--- /dev/null
+++ b/packages/core/src/video/speed-engine.test.ts
@@ -0,0 +1,174 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import { SpeedEngine } from "./speed-engine";
+
+describe("SpeedEngine", () => {
+ let speedEngine: SpeedEngine;
+
+ beforeEach(() => {
+ speedEngine = new SpeedEngine();
+ });
+
+ describe("Basic Speed Operations", () => {
+ it("should return default speed of 1 for uninitialized clips", () => {
+ expect(speedEngine.getClipSpeed("unknown-clip")).toBe(1);
+ });
+
+ it("should set and get clip speed", () => {
+ speedEngine.setClipSpeed("clip-1", 2, 10);
+ expect(speedEngine.getClipSpeed("clip-1")).toBe(2);
+ });
+
+ it("should clamp speed to valid range", () => {
+ speedEngine.setClipSpeed("clip-1", 0.01, 10);
+ expect(speedEngine.getClipSpeed("clip-1")).toBe(0.1);
+
+ speedEngine.setClipSpeed("clip-2", 100, 10);
+ expect(speedEngine.getClipSpeed("clip-2")).toBe(20);
+ });
+ });
+
+ describe("getSourceTimeAtPlaybackTime - Critical for Playback", () => {
+ it("should return same time when speed is 1x", () => {
+ speedEngine.setClipSpeed("clip-1", 1, 10);
+
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 0)).toBe(0);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 5)).toBe(5);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 10)).toBe(10);
+ });
+
+ it("should return doubled time when speed is 2x", () => {
+ speedEngine.setClipSpeed("clip-1", 2, 10);
+
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 0)).toBe(0);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 2.5)).toBe(5);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 5)).toBe(10);
+ });
+
+ it("should return halved time when speed is 0.5x", () => {
+ speedEngine.setClipSpeed("clip-1", 0.5, 10);
+
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 0)).toBe(0);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 10)).toBe(5);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 20)).toBe(10);
+ });
+
+ it("should clamp source time to valid range", () => {
+ speedEngine.setClipSpeed("clip-1", 2, 10);
+
+ const sourceTime = speedEngine.getSourceTimeAtPlaybackTime("clip-1", 100);
+ expect(sourceTime).toBeLessThanOrEqual(10);
+ });
+
+ it("should handle reverse playback", () => {
+ speedEngine.setClipSpeed("clip-1", 1, 10);
+ speedEngine.setReverse("clip-1", true, 10);
+
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 0)).toBe(10);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 5)).toBe(5);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 10)).toBe(0);
+ });
+
+ it("should handle reverse playback at 2x speed", () => {
+ speedEngine.setClipSpeed("clip-1", 2, 10);
+ speedEngine.setReverse("clip-1", true, 10);
+
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 0)).toBe(10);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 2.5)).toBe(5);
+ expect(speedEngine.getSourceTimeAtPlaybackTime("clip-1", 5)).toBe(0);
+ });
+ });
+
+ describe("Effective Duration Calculation", () => {
+ it("should calculate effective duration at 1x speed", () => {
+ speedEngine.setClipSpeed("clip-1", 1, 10);
+ expect(speedEngine.getEffectiveDuration("clip-1")).toBe(10);
+ });
+
+ it("should calculate effective duration at 2x speed", () => {
+ speedEngine.setClipSpeed("clip-1", 2, 10);
+ expect(speedEngine.getEffectiveDuration("clip-1")).toBe(5);
+ });
+
+ it("should calculate effective duration at 0.5x speed", () => {
+ speedEngine.setClipSpeed("clip-1", 0.5, 10);
+ expect(speedEngine.getEffectiveDuration("clip-1")).toBe(20);
+ });
+ });
+
+ describe("Frame Index Calculations", () => {
+ it("should get correct frame index at 1x speed", () => {
+ speedEngine.setClipSpeed("clip-1", 1, 10);
+
+ expect(speedEngine.getFrameIndexAtTime("clip-1", 0, 30)).toBe(0);
+ expect(speedEngine.getFrameIndexAtTime("clip-1", 1, 30)).toBe(30);
+ expect(speedEngine.getFrameIndexAtTime("clip-1", 2, 30)).toBe(60);
+ });
+
+ it("should get correct frame index at 2x speed", () => {
+ speedEngine.setClipSpeed("clip-1", 2, 10);
+
+ expect(speedEngine.getFrameIndexAtTime("clip-1", 0, 30)).toBe(0);
+ expect(speedEngine.getFrameIndexAtTime("clip-1", 1, 30)).toBe(60);
+ expect(speedEngine.getFrameIndexAtTime("clip-1", 2, 30)).toBe(120);
+ });
+ });
+
+ describe("Playback Timing Invariants", () => {
+ it("clipLocalTime should be independent of speed for transforms", () => {
+ const originalDuration = 10;
+ const clipStartTime = 5;
+
+ speedEngine.setClipSpeed("clip-1", 2, originalDuration);
+
+ for (let playheadTime = clipStartTime; playheadTime < clipStartTime + 5; playheadTime += 0.5) {
+ const clipLocalTime = playheadTime - clipStartTime;
+ expect(clipLocalTime).toBeGreaterThanOrEqual(0);
+ expect(clipLocalTime).toBeLessThanOrEqual(originalDuration / 2);
+ }
+ });
+
+ it("mediaTime should advance at speed rate while playhead advances at 1x", () => {
+ const speed = 2;
+ const originalDuration = 10;
+ speedEngine.setClipSpeed("clip-1", speed, originalDuration);
+
+ const realTimeElapsed = 1;
+ const expectedMediaTimeAdvance = realTimeElapsed * speed;
+
+ const mediaTime = speedEngine.getSourceTimeAtPlaybackTime("clip-1", realTimeElapsed);
+ expect(mediaTime).toBe(expectedMediaTimeAdvance);
+ });
+ });
+});
+
+describe("SpeedEngine - Playback Time vs Media Time", () => {
+ let speedEngine: SpeedEngine;
+
+ beforeEach(() => {
+ speedEngine = new SpeedEngine();
+ });
+
+ it("should correctly separate playhead time from media time at various speeds", () => {
+ const speeds = [0.5, 1, 1.5, 2, 3];
+ const originalDuration = 60;
+
+ for (const speed of speeds) {
+ speedEngine.setClipSpeed(`clip-${speed}`, speed, originalDuration);
+
+ const playbackDuration = originalDuration / speed;
+ const testPoints = [0, 0.25, 0.5, 0.75, 1];
+
+ for (const fraction of testPoints) {
+ const playheadTime = playbackDuration * fraction;
+ const expectedMediaTime = Math.min(originalDuration, playheadTime * speed);
+
+ const actualMediaTime = speedEngine.getSourceTimeAtPlaybackTime(
+ `clip-${speed}`,
+ playheadTime
+ );
+
+ expect(actualMediaTime).toBeCloseTo(expectedMediaTime, 5);
+ }
+ }
+ });
+});