🎥 Make videos programmatically with React
`@remotion/media`: Render first frame instead of throwing error for videos starting after timestamp 0
Igor Samokhovets2e74a222b782
diff --git a/packages/example-videos/videos/video-start-offset.mp4 b/packages/example-videos/videos/video-start-offset.mp4new file mode 100644index 0000000000..272a0190ceBinary files /dev/null and b/packages/example-videos/videos/video-start-offset.mp4 differdiff --git a/packages/media/src/test/video-non-zero-start.test.ts b/packages/media/src/test/video-non-zero-start.test.tsnew file mode 100644index 0000000000..c6eed096a6--- /dev/null+++ b/packages/media/src/test/video-non-zero-start.test.ts@@ -0,0 +1,120 @@+import {assert, expect, test} from 'vitest';+import {getMaxVideoCacheSize, keyframeManager} from '../caches';+import {extractFrame} from '../video-extraction/extract-frame';++test('Video frame extraction at timestamp 0 when video starts at 0.15sec', async () => {+ await keyframeManager.clearAll('info');++ // This video's first video frame is at 0.15 seconds (150ms)+ // The old tolerance was 0.1 seconds (100ms), which would have thrown an error:+ // "Timestamp is before start timestamp (requested: 0sec, start: 0.15sec, difference: 0.150sec exceeds tolerance of 0.1sec)"+ // Now we remove the tolerance check entirely and clamp to the first available frame,+ // matching Chrome's behavior of rendering the first frame rather than showing black.+ const result = await extractFrame({+ src: '/video-start-offset.mp4',+ timeInSeconds: 0,+ logLevel: 'info',+ loop: false,+ trimAfter: undefined,+ trimBefore: undefined,+ playbackRate: 1,+ fps: 30,+ maxCacheSize: getMaxVideoCacheSize('info'),+ });++ expect(result.type).toBe('success');+ assert(result.type === 'success');++ assert(result.frame, 'Frame should be returned');++ expect(result.frame.codedWidth).toBe(640);+ expect(result.frame.codedHeight).toBe(480);++ // IMPORTANT: Frame timestamp should be at video start (0.15s), NOT at requested time (0s)+ expect(result.frame.timestamp).toBeCloseTo(0.15, 2);++ await keyframeManager.clearAll('info');+});++test('Video frame extraction at exact start timestamp works', async () => {+ await keyframeManager.clearAll('info');++ const result = await extractFrame({+ src: '/video-start-offset.mp4',+ timeInSeconds: 0.15,+ logLevel: 'info',+ loop: false,+ trimAfter: undefined,+ trimBefore: undefined,+ playbackRate: 1,+ fps: 30,+ maxCacheSize: getMaxVideoCacheSize('info'),+ });++ expect(result.type).toBe('success');+ assert(result.type === 'success');+ assert(result.frame);++ expect(result.frame.timestamp).toBeCloseTo(0.15, 2);++ await keyframeManager.clearAll('info');+});++test('Video frame extraction slightly before start clamps to first frame', async () => {+ await keyframeManager.clearAll('info');++ // Requesting at 0.1 (slightly before 0.15) should clamp to 0.15+ const result = await extractFrame({+ src: '/video-start-offset.mp4',+ timeInSeconds: 0.1,+ logLevel: 'info',+ loop: false,+ trimAfter: undefined,+ trimBefore: undefined,+ playbackRate: 1,+ fps: 30,+ maxCacheSize: getMaxVideoCacheSize('info'),+ });++ expect(result.type).toBe('success');+ assert(result.type === 'success');+ assert(result.frame);++ // Should return first frame at 0.15, not an error+ expect(result.frame.timestamp).toBeCloseTo(0.15, 2);++ await keyframeManager.clearAll('info');+});++test('First frame has non-black pixel data', async () => {+ await keyframeManager.clearAll('info');++ const result = await extractFrame({+ src: '/video-start-offset.mp4',+ timeInSeconds: 0,+ logLevel: 'info',+ loop: false,+ trimAfter: undefined,+ trimBefore: undefined,+ playbackRate: 1,+ fps: 30,+ maxCacheSize: getMaxVideoCacheSize('info'),+ });++ expect(result.type).toBe('success');+ assert(result.type === 'success');+ assert(result.frame);++ // Sample pixel data from the frame to verify it's not completely black+ // testsrc generates a test pattern with colors, gradients, and timestamp overlay+ // For a 640x480 video, we need 640 * 480 * 4 bytes for RGBA+ const bufferSize = result.frame.codedWidth * result.frame.codedHeight * 4;+ const buffer = new Uint8Array(bufferSize);+ await result.frame.copyTo(buffer);++ // Check that not all pixels are zero (black)+ const hasNonZeroPixels = buffer.some((byte) => byte > 0);+ expect(hasNonZeroPixels).toBe(true);++ await keyframeManager.clearAll('info');+});diff --git a/packages/media/src/video-extraction/keyframe-bank.ts b/packages/media/src/video-extraction/keyframe-bank.tsindex 121f7cd7de..8db61d23c7 100644--- a/packages/media/src/video-extraction/keyframe-bank.ts+++ b/packages/media/src/video-extraction/keyframe-bank.ts@@ -140,30 +140,18 @@ export const makeKeyframeBank = ({): Promise<VideoSample | null> => {lastUsed = Date.now();- // Videos may start slightly after timestamp 0 due to encoding, but if the requested timestamp is too far before the bank start, something is likely wrong.- const maxClampToleranceInSeconds = 0.1;-- // If the requested timestamp is before the start of this bank, clamp it to the start if within tolerance. This handles videos that don't start at timestamp 0.- // For example, requesting frame at 0sec when video starts at 0.04sec should return the frame at 0.04sec.+ // If the requested timestamp is before the start of this bank, clamp it to the start.+ // This matches Chrome's behavior: render the first available frame rather than showing black.+ // Videos don't always start at timestamp 0 due to encoding artifacts, container format quirks,+ // and keyframe positioning. Users have no control over this, so we clamp to the first frame.// Test case: https://github.com/remotion-dev/remotion/issues/5915-let adjustedTimestamp = timestampInSeconds;if (roundTo4Digits(timestampInSeconds) <roundTo4Digits(startTimestampInSeconds)) {- const differenceInSeconds = startTimestampInSeconds - timestampInSeconds;-- if (differenceInSeconds <= maxClampToleranceInSeconds) {- adjustedTimestamp = startTimestampInSeconds;- } else {- return Promise.reject(- new Error(- `Timestamp is before start timestamp (requested: ${timestampInSeconds}sec, start: ${startTimestampInSeconds}sec, difference: ${differenceInSeconds.toFixed(3)}sec exceeds tolerance of ${maxClampToleranceInSeconds}sec)`,- ),- );- }+ adjustedTimestamp = startTimestampInSeconds;}if (