Skip to content

🎥 Make videos programmatically with React

implement smart debouncing to avoid overfetching when seeknig

Igor Samokhovetsd37f3fd81974
diff --git a/packages/media-utils/src/get-partial-media-data.ts b/packages/media-utils/src/get-partial-audio-data.ts
similarity index 86%
rename from packages/media-utils/src/get-partial-media-data.ts
rename to packages/media-utils/src/get-partial-audio-data.ts
index 566f0b505e..57d747279e 100644
--- a/packages/media-utils/src/get-partial-media-data.ts
+++ b/packages/media-utils/src/get-partial-audio-data.ts
@@ -5,7 +5,7 @@ import {
} from '@remotion/media-parser';
import {createAudioDecoder} from '@remotion/webcodecs';
-export const getPartialMediaData = async ({
+export const getPartialAudioData = async ({
src,
fromSeconds,
toSeconds,
@@ -28,6 +28,13 @@ export const getPartialMediaData = async ({
throw new Error('Operation was aborted');
}
+ // Forward abort signal immediately to the controller
+ const onAbort = () => {
+ controller.abort();
+ };
+
+ signal.addEventListener('abort', onAbort, {once: true});
+
try {
if (fromSeconds > 0) {
controller.seek(fromSeconds);
@@ -38,6 +45,11 @@ export const getPartialMediaData = async ({
src,
controller,
onAudioTrack: ({track}) => {
+ // Check abort signal immediately when onAudioTrack is called
+ if (signal.aborted) {
+ return null;
+ }
+
const audioDecoder = createAudioDecoder({
track,
onFrame: (sample) => {
@@ -80,18 +92,12 @@ export const getPartialMediaData = async ({
},
});
- // Listen for abort signal
- const onAbort = () => {
- controller.abort();
- if (audioDecoder) {
- audioDecoder.close();
- }
- };
-
- signal.addEventListener('abort', onAbort, {once: true});
+ // The abort listener is already set up above, no need to duplicate
return async (sample) => {
if (signal.aborted) {
+ audioDecoder.close();
+ controller.abort();
return;
}
@@ -122,6 +128,9 @@ export const getPartialMediaData = async ({
if (!isAbortedByTimeCutoff && !signal.aborted) {
throw err;
}
+ } finally {
+ // Clean up the event listener
+ signal.removeEventListener('abort', onAbort);
}
// Simply concatenate all audio data since windowing handles the time ranges
diff --git a/packages/media-utils/src/index.ts b/packages/media-utils/src/index.ts
index cdbc64733a..3de6801731 100644
--- a/packages/media-utils/src/index.ts
+++ b/packages/media-utils/src/index.ts
@@ -6,7 +6,7 @@ export {
getAudioDurationInSeconds,
} from './get-audio-duration-in-seconds';
export {getImageDimensions} from './get-image-dimensions';
-export {getPartialMediaData} from './get-partial-media-data';
+export {getPartialAudioData} from './get-partial-audio-data';
export {getVideoMetadata} from './get-video-metadata';
export {getWaveformPortion} from './get-waveform-portion';
export * from './types';
diff --git a/packages/media-utils/src/use-windowed-audio-data.ts b/packages/media-utils/src/use-windowed-audio-data.ts
index 69f0c8f41d..b4500f7395 100644
--- a/packages/media-utils/src/use-windowed-audio-data.ts
+++ b/packages/media-utils/src/use-windowed-audio-data.ts
@@ -9,7 +9,7 @@ import {
} from 'react';
import {cancelRender, continueRender, delayRender} from 'remotion';
import {combineFloat32Arrays} from './combine-float32-arrays';
-import {getPartialMediaData} from './get-partial-media-data';
+import {getPartialAudioData} from './get-partial-audio-data';
import {isRemoteAsset} from './is-remote-asset';
import type {MediaUtilsAudioData} from './types';
@@ -34,6 +34,10 @@ interface AudioMetadata {
sampleRate: number;
}
+const sleep = (ms: number) =>
+ // eslint-disable-next-line no-promise-executor-return
+ new Promise((resolve) => setTimeout(resolve, ms));
+
export const useWindowedAudioData = ({
src,
frame,
@@ -149,36 +153,68 @@ export const useWindowedAudioData = ({
throw new Error('Media probe is not loaded yet');
}
+ // Cancel any existing request for this window, we don't want to over-fetch
+ const existingController = requests.current[windowIndex];
+ if (existingController) {
+ existingController.abort();
+ }
+
const controller = new AbortController();
requests.current[windowIndex] = controller;
- const partialWaveData = await getPartialMediaData({
- src,
- fromSeconds: windowIndex * windowInSeconds,
- toSeconds: (windowIndex + 1) * windowInSeconds,
- channelIndex,
- signal: controller.signal,
- });
- requests.current[windowIndex] = null;
-
- setWaveformMap((prev) => {
- const entries = Object.keys(prev);
- const windowsToClear = entries.filter(
- (entry) => !windowsToFetch.includes(Number(entry)),
- );
- return {
- ...prev,
- // Delete windows that are not needed anymore
- ...windowsToClear.reduce(
- (acc, key) => {
- acc[key] = null;
- return acc;
- },
- {} as Record<string, null>,
- ),
- // Add the new window
- [windowIndex]: partialWaveData,
- };
- });
+
+ // Add a small delay to allow for rapid seeking to settle
+ // this also creates a short window for the signal to be aborted in case of super-rapid seeking
+ await sleep(250);
+
+ // Check if we were aborted during the delay
+ if (controller.signal.aborted) {
+ return;
+ }
+
+ try {
+ const partialWaveData = await getPartialAudioData({
+ src,
+ fromSeconds: windowIndex * windowInSeconds,
+ toSeconds: (windowIndex + 1) * windowInSeconds,
+ channelIndex,
+ signal: controller.signal,
+ });
+
+ // Only update if we still have a valid controller (not aborted)
+ if (!controller.signal.aborted) {
+ setWaveformMap((prev) => {
+ const entries = Object.keys(prev);
+ const windowsToClear = entries.filter(
+ (entry) => !windowsToFetch.includes(Number(entry)),
+ );
+ return {
+ ...prev,
+ // Delete windows that are not needed anymore
+ ...windowsToClear.reduce(
+ (acc, key) => {
+ acc[key] = null;
+ return acc;
+ },
+ {} as Record<string, null>,
+ ),
+ // Add the new window
+ [windowIndex]: partialWaveData,
+ };
+ });
+ }
+ } catch (err) {
+ // If the request was aborted, don't throw
+ if (controller.signal.aborted) {
+ return;
+ }
+
+ throw err;
+ } finally {
+ // Clean up the request reference
+ if (requests.current[windowIndex] === controller) {
+ requests.current[windowIndex] = null;
+ }
+ }
},
[channelIndex, src, metadata, windowInSeconds, windowsToFetch],
);