🎥 Make videos programmatically with React
`@remotion/media`: Ensure we always get the right duration from mediabunny frame by peeking (#8917)
Jonny Burgeracab81de0a56
diff --git a/packages/media/src/test/keyframe-bank.test.ts b/packages/media/src/test/keyframe-bank.test.tsindex efa7f9a922..3112e3b399 100644--- a/packages/media/src/test/keyframe-bank.test.ts+++ b/packages/media/src/test/keyframe-bank.test.ts@@ -53,3 +53,23 @@ test('a long frame duration can satisfy requests beyond the jump threshold', asybank.prepareForDeletion('error', 'test');samples[1].close();});++test('uses next sample timestamp instead of reported duration while rendering', async () => {+ const samples = [+ makeSample({timestamp: 0, duration: 10}),+ makeSample({timestamp: 1, duration: 0.1}),+ ];++ const bank = await makeKeyframeBank({+ logLevel: 'error',+ src: 'wrong-duration-frame.mp4',+ videoSampleSink: makeVideoSampleSink(samples),+ initialTimestampRequest: 0,+ });++ const frame = await bank.getFrameFromTimestamp(1.5, 30);++ expect(frame?.timestamp).toBe(1);++ bank.prepareForDeletion('error', 'test');+});diff --git a/packages/media/src/test/video-preview-iterator.test.ts b/packages/media/src/test/video-preview-iterator.test.tsnew file mode 100644index 0000000000..4e90b42d67--- /dev/null+++ b/packages/media/src/test/video-preview-iterator.test.ts@@ -0,0 +1,101 @@+import type {WrappedCanvas} from 'mediabunny';+import {expect, test} from 'vitest';+import {createVideoIterator} from '../video/video-preview-iterator';++const makeFrame = ({+ timestamp,+ duration,+}: {+ timestamp: number;+ duration: number;+}): WrappedCanvas => {+ return {+ canvas: {} as OffscreenCanvas,+ duration,+ timestamp,+ };+};++test('preview iterator uses next frame timestamp instead of reported duration', async () => {+ const frames = [+ makeFrame({timestamp: 0, duration: 0.1}),+ makeFrame({timestamp: 1, duration: 0.1}),+ makeFrame({timestamp: 2, duration: 0.1}),+ ];++ const iterator = await createVideoIterator(0, {+ destroy: () => undefined,+ makeIteratorOrUsePrewarmed: () => {+ let index = 0;++ return {+ closeIterator: () => Promise.resolve(),+ next: () => {+ const frame = frames[index++] ?? null;+ return {+ type: 'ready' as const,+ frame,+ };+ },+ };+ },+ prewarmIteratorForLooping: () => undefined,+ });++ try {+ const result = await iterator.tryToSatisfySeek(1.5);++ if (result.type !== 'satisfied') {+ throw new Error(`Expected seek to be satisfied, got ${result.reason}`);+ }++ expect(result.frame.timestamp).toBe(1);+ } finally {+ iterator.destroy();+ }+});++test('preview iterator does not trust reported duration without a next timestamp', async () => {+ const frames = [+ makeFrame({timestamp: 0, duration: 10}),+ makeFrame({timestamp: 1, duration: 10}),+ ];+ let index = 0;+ let pendingWaits = 0;++ const iterator = await createVideoIterator(0, {+ destroy: () => undefined,+ makeIteratorOrUsePrewarmed: () => {+ return {+ closeIterator: () => Promise.resolve(),+ next: () => {+ const frame = frames[index++];+ if (frame) {+ return {+ type: 'ready' as const,+ frame,+ };+ }++ return {+ type: 'pending' as const,+ wait: () => {+ pendingWaits++;+ return Promise.resolve(makeFrame({timestamp: 2, duration: 10}));+ },+ };+ },+ };+ },+ prewarmIteratorForLooping: () => undefined,+ });++ try {+ const result = await iterator.tryToSatisfySeek(1.5);++ expect(result.type).toBe('not-satisfied');+ expect(pendingWaits).toBe(0);+ } finally {+ iterator.destroy();+ }+});diff --git a/packages/media/src/video-extraction/keyframe-bank.ts b/packages/media/src/video-extraction/keyframe-bank.tsindex 5a3df1c62d..ced44d7346 100644--- a/packages/media/src/video-extraction/keyframe-bank.ts+++ b/packages/media/src/video-extraction/keyframe-bank.ts@@ -65,20 +65,41 @@ export const makeKeyframeBank = async ({let lastUsed = Date.now();let allocationSize = 0;- const getDurationOfFrame = (timestamp: number) => {+ const getMeasuredDurationOfFrame = (timestamp: number) => {const index = frameTimestamps.indexOf(timestamp);if (index === -1) {throw new Error(`Frame ${timestamp} not found`);}const nextTimestamp = frameTimestamps[index + 1];- if (!nextTimestamp) {+ if (nextTimestamp === undefined) {return null;}return nextTimestamp - timestamp;};+ const getKnownDurationOfFrame = (timestamp: number) => {+ const measuredDuration = getMeasuredDurationOfFrame(timestamp);+ if (measuredDuration !== null) {+ return measuredDuration;+ }++ if (!hasReachedEndOfVideo) {+ return null;+ }++ return (frames[timestamp] as VideoSample).duration ?? 0;+ };++ const getEstimatedDurationOfFrame = (timestamp: number) => {+ return (+ getMeasuredDurationOfFrame(timestamp) ??+ (frames[timestamp] as VideoSample).duration ??+ 0+ );+ };+const deleteFrameAtTimestamp = (timestamp: number) => {allocationSize -= getAllocationSize(frames[timestamp]);frameTimestamps.splice(frameTimestamps.indexOf(timestamp), 1);@@ -108,9 +129,10 @@ export const makeKeyframeBank = async ({continue;}- const duration =- getDurationOfFrame(frameTimestamp) ??- (frames[frameTimestamp] as VideoSample).duration;+ const duration = getKnownDurationOfFrame(frameTimestamp);+ if (duration === null) {+ continue;+ }if (frameTimestamp + duration < timestampInSeconds) {deleteFrameAtTimestamp(frameTimestamp);@@ -128,7 +150,7 @@ export const makeKeyframeBank = async ({const hasDecodedEnoughForTimestamp = (timestamp: number) => {const lastFrameTimestamp = frameTimestamps[frameTimestamps.length - 1];- if (!lastFrameTimestamp) {+ if (lastFrameTimestamp === undefined) {return false;}@@ -139,9 +161,14 @@ export const makeKeyframeBank = async ({return true;}- const duration =- getDurationOfFrame(lastFrameTimestamp) ??- (lastFrame as VideoSample).duration;+ if (roundTo4Digits(lastFrameTimestamp) >= roundTo4Digits(timestamp)) {+ return true;+ }++ const duration = getKnownDurationOfFrame(lastFrameTimestamp);+ if (duration === null) {+ return false;+ }return (roundTo4Digits(lastFrameTimestamp + duration) > roundTo4Digits(timestamp)@@ -278,14 +305,7 @@ export const makeKeyframeBank = async ({const firstTimestamp = frameTimestamps[0];const lastTimestamp = frameTimestamps[frameTimestamps.length - 1]!;- const lastFrame = frames[lastTimestamp];-- // If we have measured it by already having the next frame, use that. Otherwise,- // resort to what Mediabunny gave us.- const lastFrameDuration =- getDurationOfFrame(lastTimestamp) ??- (lastFrame as VideoSample).duration ??- 0;+ const lastFrameDuration = getEstimatedDurationOfFrame(lastTimestamp);return {firstTimestamp,diff --git a/packages/media/src/video/video-preview-iterator.ts b/packages/media/src/video/video-preview-iterator.tsindex 05c1e1d1ed..2acb008ba9 100644--- a/packages/media/src/video/video-preview-iterator.ts+++ b/packages/media/src/video/video-preview-iterator.ts@@ -3,6 +3,8 @@ import {releaseStableFrame} from '../canvas-ahead-of-time';import {roundTo4Digits} from '../helpers/round-to-4-digits';import type {PrewarmedVideoIteratorCache} from '../prewarm-iterator-for-looping';+const MAXIMUM_AWAITED_PEEK_DISTANCE_SECONDS = 0.05;+export const createVideoIterator = async (timeToSeek: number,cache: PrewarmedVideoIteratorCache,@@ -28,19 +30,76 @@ export const createVideoIterator = async (lastReturnedFrame = frame;};- const peek = async () => {+ const setPeekedFrame = (frame: WrappedCanvas | null) => {+ peekedFrame = frame;+ if (peekedFrame === null) {+ iteratorEnded = true;+ }++ return peekedFrame;+ };++ const peekIfReady = () => {if (peekedFrame) {- return peekedFrame;+ return {type: 'ready' as const, frame: peekedFrame};+ }++ if (iteratorEnded) {+ return {type: 'ready' as const, frame: null};}const next = iterator.next();if (next.type === 'ready') {- peekedFrame = next.frame;- } else {- peekedFrame = await next.wait();+ return {type: 'ready' as const, frame: setPeekedFrame(next.frame)};}- return peekedFrame;+ return {+ type: 'pending' as const,+ wait: next.wait,+ };+ };++ const peek = async () => {+ const peeked = peekIfReady();+ if (peeked.type === 'ready') {+ return peeked.frame;+ }++ return setPeekedFrame(await peeked.wait());+ };++ const getFrameEndTimestampFromPeek = (frame: WrappedCanvas | null) => {+ return frame ? roundTo4Digits(frame.timestamp) : Infinity;+ };++ const getFrameEndTimestamp = async () => {+ return getFrameEndTimestampFromPeek(await peek());+ };++ const getFrameEndTimestampIfCloseEnough = async ({+ timestamp,+ frameTimestamp,+ }: {+ timestamp: number;+ frameTimestamp: number;+ }) => {+ const peeked = peekIfReady();+ if (peeked.type === 'ready') {+ return {+ type: 'ready' as const,+ timestamp: getFrameEndTimestampFromPeek(peeked.frame),+ };+ }++ if (timestamp - frameTimestamp > MAXIMUM_AWAITED_PEEK_DISTANCE_SECONDS) {+ return {type: 'pending' as const};+ }++ const awaitedPeeked = setPeekedFrame(await peeked.wait());+ return {+ type: 'ready' as const,+ timestamp: getFrameEndTimestampFromPeek(awaitedPeeked),+ };};const getNextOrNullIfNotAvailable = () => {@@ -132,17 +191,7 @@ export const createVideoIterator = async (};}- let lastFrameDuration = lastReturnedFrame.duration;- if (lastFrameDuration === 0) {- const peeked = await peek();- if (peeked) {- lastFrameDuration = peeked.timestamp - lastReturnedFrame.timestamp;- }- }-- const frameEndTimestamp = roundTo4Digits(- lastReturnedFrame.timestamp + lastFrameDuration,- );+ const frameEndTimestamp = await getFrameEndTimestamp();if (frameTimestamp <= timestamp && frameEndTimestamp > timestamp) {return {@@ -193,10 +242,21 @@ export const createVideoIterator = async (}const frameTimestamp = roundTo4Digits(frame.frame.timestamp);- const frameEndTimestamp = roundTo4Digits(- frame.frame.timestamp + frame.frame.duration,- );- if (frameTimestamp <= timestamp && frameEndTimestamp > timestamp) {+ const frameEndTimestamp = await getFrameEndTimestampIfCloseEnough({+ frameTimestamp,+ timestamp,+ });+ if (frameEndTimestamp.type === 'pending') {+ return {+ type: 'not-satisfied' as const,+ reason: 'iterator did not have next frame ready',+ };+ }++ if (+ frameTimestamp <= timestamp &&+ frameEndTimestamp.timestamp > timestamp+ ) {return {type: 'satisfied' as const,frame: frame.frame,