🎥 Make videos programmatically with React
`@remotion/media`: Fix extra GOP decoded when seeking to fractional MP4 keyframes
Jonny Burger799276d6b984
diff --git a/packages/example-videos/videos/fractional-keyframe.mp4 b/packages/example-videos/videos/fractional-keyframe.mp4new file mode 100644index 0000000000..357ab2dc9fBinary files /dev/null and b/packages/example-videos/videos/fractional-keyframe.mp4 differdiff --git a/packages/example-videos/videos/millisecond-keyframe.webm b/packages/example-videos/videos/millisecond-keyframe.webmnew file mode 100644index 0000000000..7a14af7180Binary files /dev/null and b/packages/example-videos/videos/millisecond-keyframe.webm differdiff --git a/packages/example-videos/videos/open-gop.mp4 b/packages/example-videos/videos/open-gop.mp4new file mode 100644index 0000000000..f90adfff2eBinary files /dev/null and b/packages/example-videos/videos/open-gop.mp4 differdiff --git a/packages/media/src/test/keyframe-bank-seek.test.ts b/packages/media/src/test/keyframe-bank-seek.test.tsnew file mode 100644index 0000000000..3a119ede43--- /dev/null+++ b/packages/media/src/test/keyframe-bank-seek.test.ts@@ -0,0 +1,111 @@+import {ALL_FORMATS, Input, UrlSource, VideoSampleSink} from 'mediabunny';+import {assert, expect, test} from 'vitest';+import {+ getMaxVideoCacheSize,+ globalMediaCache,+ keyframeManager,+} from '../caches';+import {extractFrame} from '../video-extraction/extract-frame';+import {makeKeyframeBank} from '../video-extraction/keyframe-bank';++const openBankAt = async (src: string, timestamp: number) => {+ const input = new Input({+ source: new UrlSource(src),+ formats: ALL_FORMATS,+ });+ const track = await input.getPrimaryVideoTrack();+ assert(track);++ const realSink = new VideoSampleSink(track);+ const decodedTimestamps: number[] = [];+ const sink = {+ ...realSink,+ async *samples(start?: number, end?: number) {+ for await (const sample of realSink.samples(start, end)) {+ decodedTimestamps.push(sample.timestamp);+ yield sample;+ }+ },+ } as VideoSampleSink;++ const bank = await makeKeyframeBank({+ logLevel: 'error',+ src,+ videoSampleSink: sink,+ timeResolution: await track.getTimeResolution(),+ initialTimestampRequest: timestamp,+ });++ return {bank, decodedTimestamps, input};+};++// ffmpeg -f lavfi -i testsrc2=size=128x72:rate=30000/1001 -frames:v 150 \+// -c:v libx264 -g 61 -keyint_min 61 -sc_threshold 0 -bf 0 \+// -video_track_timescale 30000 fractional-keyframe.mp4+test('starts decoding at a fractional MP4 keyframe instead of the previous GOP', async () => {+ const keyframe = 61061 / 30000;+ const {bank, decodedTimestamps, input} = await openBankAt(+ '/fractional-keyframe.mp4',+ keyframe,+ );++ try {+ const frame = await bank.getFrameFromTimestamp(keyframe, 30000 / 1001);+ expect(frame?.timestamp).toBe(keyframe);+ expect(decodedTimestamps[0]).toBe(keyframe);+ } finally {+ bank.prepareForDeletion('error', 'test');+ input.dispose();+ }+});++// ffmpeg -f lavfi -i testsrc2=size=128x72:rate=30 -frames:v 130 \+// -c:v libvpx-vp9 -g 62 -keyint_min 62 millisecond-keyframe.webm+test('starts decoding at a millisecond-quantized WebM keyframe instead of the previous GOP', async () => {+ const {bank, decodedTimestamps, input} = await openBankAt(+ '/millisecond-keyframe.webm',+ 62 / 30,+ );++ try {+ const frame = await bank.getFrameFromTimestamp(62 / 30, 30);+ expect(frame?.timestamp).toBe(2.067);+ expect(decodedTimestamps[0]).toBe(2.067);+ } finally {+ bank.prepareForDeletion('error', 'test');+ input.dispose();+ }+});++// https://github.com/Vanilagy/mediabunny/issues/269+// Open GOP with B-frames: the keyframe at 1.6667s is stored before the frame at 1.6333s.+// ffmpeg -f lavfi -i testsrc2=size=128x72:rate=30 -frames:v 150 -c:v libx264 -bf 3 \+// -x264-params open-gop=1:keyint=50:min-keyint=50:scenecut=0 open-gop.mp4+test('does not skip frames around reordered open-GOP keyframes', async () => {+ keyframeManager.clearAll('info');++ for (let i = 40; i <= 60; i++) {+ const result = await extractFrame({+ src: '/open-gop.mp4',+ timeInSeconds: i / 30,+ logLevel: 'info',+ loop: false,+ trimAfter: undefined,+ trimBefore: undefined,+ playbackRate: 1,+ fps: 30,+ maxCacheSize: getMaxVideoCacheSize('info'),+ credentials: undefined,+ mediaCache: globalMediaCache,+ });++ assert(result.type === 'success');+ assert(result.frame);+ expect(+ Math.abs(result.frame.timestamp - (i / 30) * 1_000_000),+ ).toBeLessThan(1000);+ result.frame.close();+ }++ keyframeManager.clearAll('info');+});diff --git a/packages/media/src/test/keyframe-bank.test.ts b/packages/media/src/test/keyframe-bank.test.tsindex 6c5424bd4a..289738055e 100644--- a/packages/media/src/test/keyframe-bank.test.ts+++ b/packages/media/src/test/keyframe-bank.test.ts@@ -44,6 +44,7 @@ test('a long frame duration can satisfy requests beyond the jump threshold', asylogLevel: 'error',src: 'long-duration-frame.mp4',videoSampleSink: makeVideoSampleSink(samples),+ timeResolution: 1000,initialTimestampRequest: 0,});@@ -91,6 +92,7 @@ test('releases old frames before requesting more decoder output', async () => {logLevel: 'error',src: 'limited-decoder-surfaces.mp4',videoSampleSink: sink,+ timeResolution: 1000,initialTimestampRequest: 0,});@@ -114,6 +116,7 @@ test('uses next sample timestamp instead of reported duration while rendering',logLevel: 'error',src: 'wrong-duration-frame.mp4',videoSampleSink: makeVideoSampleSink(samples),+ timeResolution: 1000,initialTimestampRequest: 0,});diff --git a/packages/media/src/test/multi-playhead-clearing.test.ts b/packages/media/src/test/multi-playhead-clearing.test.tsindex 49426fea04..b9997e4405 100644--- a/packages/media/src/test/multi-playhead-clearing.test.ts+++ b/packages/media/src/test/multi-playhead-clearing.test.ts@@ -56,6 +56,7 @@ test('concurrent playheads on the same src do not clear each other`s banks', asyconst bank = await manager.requestKeyframeBank({timestamp,videoSampleSink: sink,+ timeResolution: 1000,src,logLevel: 'error',maxCacheSize: 100 * 1024 * 1024,@@ -89,6 +90,7 @@ test('banks that are no longer being read still get cleared', async () => {const bank = await manager.requestKeyframeBank({timestamp,videoSampleSink: sink,+ timeResolution: 1000,src,logLevel: 'error',maxCacheSize: 100 * 1024 * 1024,@@ -152,6 +154,7 @@ test('a bank is not cleared while it is decoding a frame', async () => {manager.requestKeyframeBank({timestamp,videoSampleSink: sink,+ timeResolution: 1000,src: 'same-video.mp4',logLevel: 'error',maxCacheSize: 100 * 1024 * 1024,diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.tsindex 7da53c37fb..dd5c4423d6 100644--- a/packages/media/src/video-extraction/extract-frame.ts+++ b/packages/media/src/video-extraction/extract-frame.ts@@ -118,6 +118,7 @@ const extractFrameInternal = async ({try {const keyframeBank = await mediaCache.keyframeManager.requestKeyframeBank({videoSampleSink: video.sampleSink,+ timeResolution: video.timeResolution,timestamp: timeInSeconds,src,logLevel,diff --git a/packages/media/src/video-extraction/get-frames-since-keyframe.ts b/packages/media/src/video-extraction/get-frames-since-keyframe.tsindex 7d5631297c..6b958de447 100644--- a/packages/media/src/video-extraction/get-frames-since-keyframe.ts+++ b/packages/media/src/video-extraction/get-frames-since-keyframe.ts@@ -22,6 +22,7 @@ import {rememberActualMatroskaTimestamps} from './remember-actual-matroska-timestype VideoSinks = {sampleSink: VideoSampleSink;+ timeResolution: number;};type AudioSinks = {@@ -137,6 +138,7 @@ export const makeSinks = (return {sampleSink,+ timeResolution: await videoTrack.getTimeResolution(),};};diff --git a/packages/media/src/video-extraction/keyframe-bank.ts b/packages/media/src/video-extraction/keyframe-bank.tsindex 78123b0512..03229c8cd2 100644--- a/packages/media/src/video-extraction/keyframe-bank.ts+++ b/packages/media/src/video-extraction/keyframe-bank.ts@@ -48,15 +48,20 @@ export const makeKeyframeBank = async ({logLevel: parentLogLevel,src,videoSampleSink,+ timeResolution,initialTimestampRequest,}: {logLevel: LogLevel;src: string;videoSampleSink: VideoSampleSink;+ timeResolution: number;initialTimestampRequest: number;}) => {+ // Snap to the track's own timestamp grid: WebM stores milliseconds, so frame 62+ // at 30fps (2.0667s) is stored at 2.067s and must not seek into the previous GOP.+ // MP4 timescales like 30000 keep fractional keyframes such as 61061/30000 exact.const sampleIterator = videoSampleSink.samples(- roundTo4Digits(initialTimestampRequest),+ Math.round(initialTimestampRequest * timeResolution) / timeResolution,);const frames: Record<number, VideoSampleWithoutDuration> = {};diff --git a/packages/media/src/video-extraction/keyframe-manager.ts b/packages/media/src/video-extraction/keyframe-manager.tsindex 7872864a6b..7468bdf336 100644--- a/packages/media/src/video-extraction/keyframe-manager.ts+++ b/packages/media/src/video-extraction/keyframe-manager.ts@@ -252,11 +252,13 @@ export const makeKeyframeManager = ({const getKeyframeBankOrRefetch = async ({timestamp,videoSampleSink,+ timeResolution,src,logLevel,}: {timestamp: number;videoSampleSink: VideoSampleSink;+ timeResolution: number;src: string;logLevel: LogLevel;}): Promise<KeyframeBank | null> => {@@ -276,6 +278,7 @@ export const makeKeyframeManager = ({);const newKeyframeBank = await makeKeyframeBank({videoSampleSink,+ timeResolution,logLevel,src,initialTimestampRequest: timestamp,@@ -310,6 +313,7 @@ export const makeKeyframeManager = ({// Then refetchconst replacementKeybank = await makeKeyframeBank({videoSampleSink,+ timeResolution,initialTimestampRequest: timestamp,logLevel,src,@@ -325,6 +329,7 @@ export const makeKeyframeManager = ({const requestKeyframeBank = async ({timestamp,videoSampleSink,+ timeResolution,src,logLevel,maxCacheSize,@@ -332,6 +337,7 @@ export const makeKeyframeManager = ({}: {timestamp: number;videoSampleSink: VideoSampleSink;+ timeResolution: number;src: string;logLevel: LogLevel;maxCacheSize: number;@@ -355,6 +361,7 @@ export const makeKeyframeManager = ({const keyframeBank = await getKeyframeBankOrRefetch({timestamp,videoSampleSink,+ timeResolution,src,logLevel,});@@ -397,6 +404,7 @@ export const makeKeyframeManager = ({requestKeyframeBank: ({timestamp,videoSampleSink,+ timeResolution,src,logLevel,maxCacheSize,@@ -404,6 +412,7 @@ export const makeKeyframeManager = ({}: {timestamp: number;videoSampleSink: VideoSampleSink;+ timeResolution: number;src: string;logLevel: LogLevel;maxCacheSize: number;@@ -413,6 +422,7 @@ export const makeKeyframeManager = ({requestKeyframeBank({timestamp,videoSampleSink,+ timeResolution,src,logLevel,maxCacheSize,