Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Properly clean up MediaElementAudioSourceNode

Jonny Burger58fba14223c8
diff --git a/packages/core/src/audio/AudioForPreview.tsx b/packages/core/src/audio/AudioForPreview.tsx
index e8507fe729..03d21105c6 100644
--- a/packages/core/src/audio/AudioForPreview.tsx
+++ b/packages/core/src/audio/AudioForPreview.tsx
@@ -165,7 +165,11 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
],
);
- const {el: audioRef, mediaElementSourceNode} = useSharedAudio({
+ const {
+ el: audioRef,
+ mediaElementSourceNode,
+ cleanupOnMediaTagUnmount,
+ } = useSharedAudio({
aud: propsToPass,
audioId: id,
premounting: Boolean(sequenceContext?.premounting),
@@ -219,6 +223,27 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
shouldUseWebAudioApi: useWebAudioApi ?? false,
});
+ /**
+ * Effects in React 18 fire twice, and we are looking for a way to only fire it once.
+ * - useInsertionEffect only fires once. If it's available we are in React 18.
+ * - useLayoutEffect only fires once in React 17.
+ *
+ * Need to import it from React to fix React 17 ESM support.
+ */
+ const effectToUse = React.useInsertionEffect ?? React.useLayoutEffect;
+
+ // Disconnecting the SharedElementSourceNodes if the Player unmounts to prevent leak.
+ // https://github.com/remotion-dev/remotion/issues/6285
+ // But useInsertionEffect will fire before other effects, meaning the
+ // nodes might still be used. Using rAF to ensure it's after other effects.
+ effectToUse(() => {
+ return () => {
+ requestAnimationFrame(() => {
+ cleanupOnMediaTagUnmount();
+ });
+ };
+ }, [mediaElementSourceNode]);
+
useImperativeHandle(ref, () => {
return audioRef.current as HTMLAudioElement;
}, [audioRef]);
diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsx
index 19f84161ad..49a8dd00a0 100644
--- a/packages/core/src/audio/shared-audio-tags.tsx
+++ b/packages/core/src/audio/shared-audio-tags.tsx
@@ -36,6 +36,7 @@ type AudioElem = {
premounting: boolean;
postmounting: boolean;
audioMounted: boolean;
+ cleanupOnMediaTagUnmount: () => void;
};
const EMPTY_AUDIO =
@@ -151,6 +152,29 @@ export const SharedAudioContextProvider: React.FC<{
});
}, [audioContext, numberOfAudioTags]);
+ /**
+ * Effects in React 18 fire twice, and we are looking for a way to only fire it once.
+ * - useInsertionEffect only fires once. If it's available we are in React 18.
+ * - useLayoutEffect only fires once in React 17.
+ *
+ * Need to import it from React to fix React 17 ESM support.
+ */
+ const effectToUse = React.useInsertionEffect ?? React.useLayoutEffect;
+
+ // Disconnecting the SharedElementSourceNodes if the Player unmounts to prevent leak.
+ // https://github.com/remotion-dev/remotion/issues/6285
+ // But useInsertionEffect will fire before other effects, meaning the
+ // nodes might still be used. Using rAF to ensure it's after other effects.
+ effectToUse(() => {
+ return () => {
+ requestAnimationFrame(() => {
+ refs.forEach(({mediaElementSourceNode}) => {
+ mediaElementSourceNode?.cleanup();
+ });
+ });
+ };
+ }, [refs]);
+
const takenAudios = useRef<(false | number)[]>(
new Array(numberOfAudioTags).fill(false),
);
@@ -220,6 +244,9 @@ export const SharedAudioContextProvider: React.FC<{
premounting,
audioMounted: Boolean(ref.current),
postmounting,
+ cleanupOnMediaTagUnmount: () => {
+ // Don't disconnect here, only when the Player unmounts.
+ },
};
audios.current?.push(newElem);
rerenderAudios();
@@ -380,6 +407,7 @@ export const useSharedAudio = ({
return ctx.registerAudio({aud, audioId, premounting, postmounting});
}
+ // numberOfSharedAudioTags is 0
const el = React.createRef<HTMLAudioElement>();
const mediaElementSourceNode = ctx?.audioContext
? makeSharedElementSourceNode({
@@ -397,6 +425,9 @@ export const useSharedAudio = ({
premounting,
audioMounted: Boolean(el.current),
postmounting,
+ cleanupOnMediaTagUnmount: () => {
+ mediaElementSourceNode?.cleanup();
+ },
};
});
diff --git a/packages/core/src/audio/shared-element-source-node.ts b/packages/core/src/audio/shared-element-source-node.ts
index 53b77e14b1..e29b33436d 100644
--- a/packages/core/src/audio/shared-element-source-node.ts
+++ b/packages/core/src/audio/shared-element-source-node.ts
@@ -6,9 +6,15 @@ export const makeSharedElementSourceNode = ({
ref: React.RefObject<HTMLAudioElement | null>;
}) => {
let connected: MediaElementAudioSourceNode | null = null;
+ let disposed = false;
+ // We must allow this to cleanup and create a new one due to strict mode.
return {
attemptToConnect: () => {
+ if (disposed) {
+ throw new Error('SharedElementSourceNode has been disposed');
+ }
+
if (!connected && ref.current) {
const mediaElementSourceNode = audioContext.createMediaElementSource(
ref.current,
@@ -24,6 +30,14 @@ export const makeSharedElementSourceNode = ({
return connected;
},
+ cleanup: () => {
+ if (connected) {
+ connected.disconnect();
+ connected = null;
+ }
+
+ disposed = true;
+ },
};
};
diff --git a/packages/core/src/video/VideoForPreview.tsx b/packages/core/src/video/VideoForPreview.tsx
index afb3559908..695f93c139 100644
--- a/packages/core/src/video/VideoForPreview.tsx
+++ b/packages/core/src/video/VideoForPreview.tsx
@@ -70,6 +70,27 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<
});
}, [context.audioContext]);
+ /**
+ * Effects in React 18 fire twice, and we are looking for a way to only fire it once.
+ * - useInsertionEffect only fires once. If it's available we are in React 18.
+ * - useLayoutEffect only fires once in React 17.
+ *
+ * Need to import it from React to fix React 17 ESM support.
+ */
+ const effectToUse = React.useInsertionEffect ?? React.useLayoutEffect;
+
+ // Disconnecting the SharedElementSourceNodes if the tag unmounts to prevent leak.
+ // https://github.com/remotion-dev/remotion/issues/6285
+ // But useInsertionEffect will fire before other effects, meaning the
+ // nodes might still be used. Using rAF to ensure it's after other effects.
+ effectToUse(() => {
+ return () => {
+ requestAnimationFrame(() => {
+ sharedSource?.cleanup();
+ });
+ };
+ }, [sharedSource]);
+
const {
volume,
muted,