Skip to content

πŸŽ₯ Make videos programmatically with React

@remotion/media-utils: Capture initial requestInit in hooks; docs v4.0.456

Jonny Burger0d427d46f2a7
diff --git a/packages/bundler/src/setup-sequence-stack-traces.ts b/packages/bundler/src/setup-sequence-stack-traces.ts
index 18bce3d842..300698d1f4 100644
--- a/packages/bundler/src/setup-sequence-stack-traces.ts
+++ b/packages/bundler/src/setup-sequence-stack-traces.ts
@@ -21,6 +21,7 @@ const enableProxy = <
apply(target, thisArg, argArray) {
if (componentsToAddStacksTo.includes(argArray[0])) {
const [first, props, ...rest] = argArray;
+ console.log('adding to', argArray[0], props);
const newProps = props?.stack
? props
: {
diff --git a/packages/docs/docs/client-side-rendering/limitations.mdx b/packages/docs/docs/client-side-rendering/limitations.mdx
index d70dcad82e..de549c12cd 100644
--- a/packages/docs/docs/client-side-rendering/limitations.mdx
+++ b/packages/docs/docs/client-side-rendering/limitations.mdx
@@ -122,6 +122,7 @@ The [`<Audio>`](/docs/media/audio) from `@remotion/media` is <a style={{color: '
[`<ThreeCanvas>`](/docs/three-canvas) from [`@remotion/three`](/docs/three) is <a style={{color: 'green'}}>supported</a>.
[`<SkiaCanvas>`](/docs/skia/skia-canvas) from [`@remotion/skia`](/docs/skia) is <a style={{color: 'green'}}>supported</a>.
[`<AnimatedImage>`](/docs/animatedimage) is <a style={{color: 'green'}}>supported</a> when rendering in Chrome.
+[`<HtmlInCanvas>`](/docs/html-in-canvas) is <a style={{color: 'green'}}>supported</a> when the component itself is supported.
[`<OffthreadVideo>`](/docs/offthreadvideo) is <a style={{color: 'red'}}>not supported</a>.
β†’ Use [`<Video>`](/docs/media/video) instead.
[`<Html5Video>`](/docs/html5-video) is <a style={{color: 'red'}}>not supported</a>.
diff --git a/packages/docs/docs/get-audio-data.mdx b/packages/docs/docs/get-audio-data.mdx
index 707ee8836b..d20ff7599c 100644
--- a/packages/docs/docs/get-audio-data.mdx
+++ b/packages/docs/docs/get-audio-data.mdx
@@ -46,10 +46,12 @@ The `sampleRate` that should be passed into the [`AudioContext`](https://develop
In versions before 4.0.121, the default value was `undefined`, leading to undeterministic behavior across devices rendering.
-#### `requestInit?`<AvailableFrom v="4.0.454"/>
+#### `requestInit?`<AvailableFrom v="4.0.456"/>
_`RequestInit`_
+Requires **Remotion v4.0.456** or newer (not released on npm yet β€” follow the [changelog](https://www.remotion.dev/changelog)).
+
Options that are passed to the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) call when loading the audio source.
This can be used to load authenticated remote audio files:
diff --git a/packages/docs/docs/three.mdx b/packages/docs/docs/three.mdx
index 5380c0c88d..1d6b722926 100644
--- a/packages/docs/docs/three.mdx
+++ b/packages/docs/docs/three.mdx
@@ -16,7 +16,7 @@ is a package for integrating [React Three Fiber](https://github.com/pmndrs/react
- [`useVideoTexture()`](/docs/use-video-texture) allows you to use a Remotion [`<Html5Video />`](/docs/html5-video) as a texture map.
-- [`useOffthreadVideoTexture()`](/docs/use-offthread-video-texture) is an equivalent to [`useVideoTexture()`](/docs/use-video-texture), but displays the exact frame as an `Three.ImageTexture` during rendering, simillarly to [`<OffthreadVideo />`](/docs/offthreadvideo).
+- [`useOffthreadVideoTexture()`](/docs/use-offthread-video-texture) is an equivalent to [`useVideoTexture()`](/docs/use-video-texture), but displays the exact frame as an `Three.ImageTexture` during rendering, similarly to [`<OffthreadVideo />`](/docs/offthreadvideo).
These are the only two APIs provided - for everything else you can use the standard [React Three Fiber](https://github.com/pmndrs/react-three-fiber) APIs.
diff --git a/packages/docs/docs/use-audio-data.mdx b/packages/docs/docs/use-audio-data.mdx
index 53df5acdcb..2f5b5a340f 100644
--- a/packages/docs/docs/use-audio-data.mdx
+++ b/packages/docs/docs/use-audio-data.mdx
@@ -38,19 +38,23 @@ Remote audio files need to support [CORS](https://developer.mozilla.org/en-US/do
</details>
:::
+:::note
+The optional `options` argument below requires **Remotion v4.0.456** or newer. That release is not out on npm yet β€” watch the [changelog](https://www.remotion.dev/changelog).
+:::
+
## Arguments
### `src`
A string pointing to an audio asset.
-### `options?`<AvailableFrom v="4.0.454"/>
+### `options?`<AvailableFrom v="4.0.456"/>
-#### `sampleRate?`<AvailableFrom v="4.0.454"/>
+#### `sampleRate?`<AvailableFrom v="4.0.456"/>
The `sampleRate` that should be passed into the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/AudioContext) constructor. If not provided, the default value is `48000`.
-#### `requestInit?`<AvailableFrom v="4.0.454"/>
+#### `requestInit?`<AvailableFrom v="4.0.456"/>
_`RequestInit`_
@@ -77,6 +81,8 @@ export const MyComponent: React.FC = () => {
};
```
+Only the `requestInit` from the **first** render is used; updates on later renders are ignored. That keeps hook dependencies stable when you pass an inline object every render (for example `{credentials: 'include'}`).
+
## Return value
`AudioData | null` - An object containing audio data (see documentation of [`getAudioData()`](/docs/get-audio-data)) or `null` if the data has not been loaded.
diff --git a/packages/docs/docs/use-windowed-audio-data.mdx b/packages/docs/docs/use-windowed-audio-data.mdx
index 050d6500e4..3e7c96bd3a 100644
--- a/packages/docs/docs/use-windowed-audio-data.mdx
+++ b/packages/docs/docs/use-windowed-audio-data.mdx
@@ -102,10 +102,12 @@ The function will load the audio data around the current frame and the windows b
In this example, the window is 10 seconds long, so the function will load the current window as well as the previous and next one, leading to up to 30 seconds of audio being loaded at a time.
-### `requestInit?`<AvailableFrom v="4.0.454"/>
+### `requestInit?`<AvailableFrom v="4.0.456"/>
_`RequestInit`_
+Requires **Remotion v4.0.456** or newer (not released on npm yet β€” follow the [changelog](https://www.remotion.dev/changelog)).
+
Options that are passed to the requests that load the audio source.
This can be used to load authenticated remote audio files:
@@ -132,6 +134,8 @@ export const MyComponent: React.FC = () => {
};
```
+Only the `requestInit` from the **first** render is used; updates on later renders are ignored. That keeps hook dependencies stable when you pass an inline object every render (for example `{credentials: 'include'}`).
+
## Return value
An object with:
diff --git a/packages/example/src/NewVideo.tsx b/packages/example/src/NewVideo.tsx
index fd1565a409..736cbf2d44 100644
--- a/packages/example/src/NewVideo.tsx
+++ b/packages/example/src/NewVideo.tsx
@@ -1,5 +1,5 @@
import {Video} from '@remotion/media';
-import {CalculateMetadataFunction, Composition} from 'remotion';
+import {CalculateMetadataFunction, Composition, Sequence} from 'remotion';
// https://www.remotion.dev/docs/mediabunny/metadata
import {getMediaMetadata} from './get-media-metadata';
@@ -19,7 +19,11 @@ export const calculateMetadataFn: CalculateMetadataFunction<
};
export const Component = () => {
- return <Video src={src} debugOverlay />;
+ return (
+ <Sequence from={30}>
+ <Video src={src} debugOverlay trimAfter={100} loop />;
+ </Sequence>
+ );
};
export const NewVideoComp = () => {
diff --git a/packages/media-utils/src/serialize-request-init.ts b/packages/media-utils/src/serialize-request-init.ts
deleted file mode 100644
index baf63ee4b1..0000000000
--- a/packages/media-utils/src/serialize-request-init.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-const normalizeHeaders = (headers: HeadersInit | undefined) => {
- if (!headers) {
- return null;
- }
-
- if (typeof Headers !== 'undefined' && headers instanceof Headers) {
- return Array.from(headers.entries()).sort(([a], [b]) => a.localeCompare(b));
- }
-
- if (Array.isArray(headers)) {
- return [...headers].sort(([a], [b]) => a.localeCompare(b));
- }
-
- return Object.entries(headers).sort(([a], [b]) => a.localeCompare(b));
-};
-
-export const serializeRequestInit = (
- requestInit: RequestInit | undefined,
-): string | null => {
- if (!requestInit) {
- return null;
- }
-
- const {headers, signal, ...rest} = requestInit;
-
- return JSON.stringify({
- ...rest,
- headers: normalizeHeaders(headers),
- signal: signal ? signal.aborted : null,
- });
-};
diff --git a/packages/media-utils/src/use-audio-data.ts b/packages/media-utils/src/use-audio-data.ts
index bc25ff34b3..396cca35fc 100644
--- a/packages/media-utils/src/use-audio-data.ts
+++ b/packages/media-utils/src/use-audio-data.ts
@@ -1,11 +1,15 @@
import {useCallback, useEffect, useLayoutEffect, useRef, useState} from 'react';
import {cancelRender, useDelayRender} from 'remotion';
import {getAudioData} from './get-audio-data';
-import {serializeRequestInit} from './serialize-request-init';
import type {MediaUtilsAudioData} from './types';
type UseAudioDataOptions = {
sampleRate?: number;
+ /**
+ * Captured only from the first render and passed to `fetch()`.
+ * Updates after mount are ignored so hooks do not depend on a new object
+ * identity every render (e.g. inline `{credentials: 'include'}`).
+ */
requestInit?: RequestInit;
};
@@ -34,40 +38,29 @@ export const useAudioData = (
const [metadata, setMetadata] = useState<MediaUtilsAudioData | null>(null);
const {delayRender, continueRender} = useDelayRender();
const sampleRate = options?.sampleRate;
- const requestInit = options?.requestInit;
- const requestInitKey = serializeRequestInit(requestInit);
- const requestInitRef = useRef(requestInit);
- requestInitRef.current = requestInit;
+ const [initialRequestInit] = useState(options?.requestInit);
- const fetchMetadata = useCallback(
- async () => {
- const handle = delayRender(
- `Waiting for audio metadata with src="${src}" to be loaded`,
- );
+ const fetchMetadata = useCallback(async () => {
+ const handle = delayRender(
+ `Waiting for audio metadata with src="${src}" to be loaded`,
+ );
- try {
- const data = await getAudioData(
- src,
- sampleRate === undefined && requestInitRef.current === undefined
- ? undefined
- : {sampleRate, requestInit: requestInitRef.current},
- );
- if (mountState.current.isMounted) {
- setMetadata(data);
- }
- } catch (err) {
- cancelRender(err);
+ try {
+ const data = await getAudioData(
+ src,
+ sampleRate === undefined && initialRequestInit === undefined
+ ? undefined
+ : {sampleRate, requestInit: initialRequestInit},
+ );
+ if (mountState.current.isMounted) {
+ setMetadata(data);
}
+ } catch (err) {
+ cancelRender(err);
+ }
- continueRender(handle);
- },
- // requestInitKey is included so the callback re-runs when the
- // serialized requestInit changes; the value itself is read via
- // requestInitRef.current to avoid recreating the callback on every
- // render when an inline object is passed.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [src, sampleRate, requestInitKey, delayRender, continueRender],
- );
+ continueRender(handle);
+ }, [src, sampleRate, initialRequestInit, delayRender, continueRender]);
useLayoutEffect(() => {
fetchMetadata();
diff --git a/packages/media-utils/src/use-windowed-audio-data.ts b/packages/media-utils/src/use-windowed-audio-data.ts
index f2bb1be2f8..4aa7518fce 100644
--- a/packages/media-utils/src/use-windowed-audio-data.ts
+++ b/packages/media-utils/src/use-windowed-audio-data.ts
@@ -19,7 +19,6 @@ import {cancelRender, Internals, useDelayRender} from 'remotion';
import {combineFloat32Arrays} from './combine-float32-arrays';
import {getPartialAudioData} from './get-partial-audio-data';
import {isRemoteAsset} from './is-remote-asset';
-import {serializeRequestInit} from './serialize-request-init';
import type {MediaUtilsAudioData} from './types';
type WaveformMap = Record<number, Float32Array>;
@@ -32,6 +31,11 @@ export type UseWindowedAudioDataOptions = {
fps: number;
windowInSeconds: number;
channelIndex?: number;
+ /**
+ * Captured only from the first render and passed to Mediabunny `UrlSource`.
+ * Updates after mount are ignored so hooks do not depend on a new object
+ * identity every render (e.g. inline `{credentials: 'include'}`).
+ */
requestInit?: RequestInit;
};
@@ -66,9 +70,7 @@ export const useWindowedAudioData = ({
const [waveFormMap, setWaveformMap] = useState({} as WaveformMap);
const requests = useRef<Record<string, AbortController | null>>({});
const [initialWindowInSeconds] = useState(windowInSeconds);
- const requestInitKey = serializeRequestInit(requestInit);
- const requestInitRef = useRef(requestInit);
- requestInitRef.current = requestInit;
+ const [initialRequestInit] = useState(requestInit);
if (windowInSeconds !== initialWindowInSeconds) {
throw new Error('windowInSeconds cannot be changed dynamically');
@@ -112,9 +114,7 @@ export const useWindowedAudioData = ({
formats: ALL_FORMATS,
source: new UrlSource(
src,
- requestInitRef.current
- ? {requestInit: requestInitRef.current}
- : undefined,
+ initialRequestInit ? {requestInit: initialRequestInit} : undefined,
),
});
@@ -177,12 +177,7 @@ export const useWindowedAudioData = ({
signal.removeEventListener('abort', onAbort);
}
},
- // requestInitKey is included so the callback re-runs when the
- // serialized requestInit changes; the value itself is read via
- // requestInitRef.current to avoid recreating the callback on every
- // render when an inline object is passed.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [src, delayRender, continueRender, channelIndex, requestInitKey],
+ [src, delayRender, continueRender, channelIndex, initialRequestInit],
);
useLayoutEffect(() => {