Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Fix extracting frames from video after it ended

Jonny Burger45e2a79dbc25
diff --git a/packages/media/src/audio-extraction/audio-cache.ts b/packages/media/src/audio-extraction/audio-cache.ts
index dc80599ed4..e556bfd743 100644
--- a/packages/media/src/audio-extraction/audio-cache.ts
+++ b/packages/media/src/audio-extraction/audio-cache.ts
@@ -14,6 +14,11 @@ export const makeAudioCache = () => {
const endTimestamp = timestamp + samples[timestamp].duration;
if (endTimestamp < threshold) {
+ const isLast = timestamp === timestamps[timestamps.length - 1];
+ if (isLast) {
+ continue;
+ }
+
samples[timestamp].close();
delete samples[timestamp];
timestamps.splice(timestamps.indexOf(timestamp), 1);
diff --git a/packages/media/src/audio-extraction/audio-iterator.ts b/packages/media/src/audio-extraction/audio-iterator.ts
index 30e648bec8..c88e0f92c3 100644
--- a/packages/media/src/audio-extraction/audio-iterator.ts
+++ b/packages/media/src/audio-extraction/audio-iterator.ts
@@ -85,11 +85,18 @@ export const makeAudioIterator = ({
);
while (true) {
+ const sample = await getNextSample();
+
// Clear all samples before the timestamp
// Do this in the while loop because samples might start from 0
- cache.clearBeforeThreshold(timestamp - SAFE_BACK_WINDOW_IN_SECONDS);
+ // Also do this after a sample has just been added, if it was the last sample we now have the duration
+ // and can prevent deleting the last sample
+
+ const deleteBefore =
+ fullDuration === null ? timestamp : Math.min(timestamp, fullDuration);
+
+ cache.clearBeforeThreshold(deleteBefore - SAFE_BACK_WINDOW_IN_SECONDS);
- const sample = await getNextSample();
if (sample === null) {
break;
}
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index ee6ea81888..7220ed29c6 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -33,6 +33,29 @@ test('Should be able to extract a frame', async () => {
expect(cacheStats.count).toBe(25);
});
+test('Should be able to extract the last frame', async () => {
+ await keyframeManager.clearAll();
+
+ const {audio, frame} = await extractFrameAndAudio({
+ src: '/bigbuckbunny.mp4',
+ timeInSeconds: 1_000_000,
+ durationInSeconds: 1 / 30,
+ logLevel: 'info',
+ includeAudio: true,
+ includeVideo: true,
+ volume: 1,
+ loop: false,
+ });
+
+ assert(frame);
+ expect(frame.timestamp).toBe(59_958_333);
+
+ assert(!audio);
+
+ const cacheStats = await keyframeManager.getCacheStats();
+ expect(cacheStats.count).toBe(93);
+});
+
test('Should manage the cache', async () => {
await keyframeManager.clearAll();
for (let i = 0; i < 50; i++) {