Skip to content

🎥 Make videos programmatically with React

handle playback rate case

Jonny Burger16c23d627c6f
diff --git a/package.json b/package.json
index 81b6a89337..b789895f67 100644
--- a/package.json
+++ b/package.json
@@ -16,6 +16,7 @@
"watch": "turbo watch make --concurrency=2 --experimental-write-cache --ui=tui",
"watchwebcodecs": "turbo watch make --experimental-write-cache --filter='@remotion/media-parser' --filter='@remotion/webcodecs'",
"watchcore": "turbo watch make --experimental-write-cache --filter='remotion'",
+ "watchplayer": "turbo watch make --experimental-write-cache --filter='@remotion/player'",
"watchstudio": "turbo watch make --experimental-write-cache --filter='@remotion/studio' --filter='@remotion/studio-server'",
"watchserverless": "turbo watch make --experimental-write-cache --filter='@remotion/lambda' --filter='@remotion/serverless' --filter='@remotion/streaming'",
"release-alpha": "pnpm recursive publish --tag=alpha --no-git-checks && pnpm recursive run --sequential publishprivate",
diff --git a/packages/core/src/audio/AudioForPreview.tsx b/packages/core/src/audio/AudioForPreview.tsx
index 9f03691f56..c6a306f849 100644
--- a/packages/core/src/audio/AudioForPreview.tsx
+++ b/packages/core/src/audio/AudioForPreview.tsx
@@ -159,13 +159,8 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
isPremounting: Boolean(sequenceContext?.premounting),
});
- useVolume({
- logLevel,
- mediaRef: audioRef,
- source: mediaElementSourceNode,
- volume: userPreferredVolume,
- });
-
+ // putting playback before useVolume
+ // because volume looks at playbackrate
useMediaPlayback({
mediaRef: audioRef,
src,
@@ -178,6 +173,13 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
onAutoPlayError: null,
});
+ useVolume({
+ logLevel,
+ mediaRef: audioRef,
+ source: mediaElementSourceNode,
+ volume: userPreferredVolume,
+ });
+
useImperativeHandle(ref, () => {
return audioRef.current as HTMLAudioElement;
}, [audioRef]);
diff --git a/packages/core/src/use-amplification.ts b/packages/core/src/use-amplification.ts
index a70f2598ff..1ad2f38acb 100644
--- a/packages/core/src/use-amplification.ts
+++ b/packages/core/src/use-amplification.ts
@@ -3,11 +3,36 @@ import {SharedAudioContext} from './audio/shared-audio-tags';
import type {SharedElementSourceNode} from './audio/shared-element-source-node';
import type {LogLevel} from './log';
import {Log} from './log';
+import {isSafari} from './video/video-fragment';
type AudioItems = {
gainNode: GainNode;
};
+let warned = false;
+
+const warnSafariOnce = (logLevel: LogLevel) => {
+ if (warned) {
+ return;
+ }
+
+ warned = true;
+ Log.warn(
+ logLevel,
+ 'In Safari, setting a volume and a playback rate at the same time is buggy.',
+ );
+ Log.warn(logLevel, 'In Desktop Safari, only volumes <= 1 will be applied.');
+ Log.warn(
+ logLevel,
+ 'In Mobile Safari, the volume will be ignored and set to 1 if a playbackRate is set.',
+ );
+};
+
+/**
+ * [1] Bug case: In Safari, you cannot combine playbackRate and volume !== 1.
+ * If that is the case, volume will not be applied.
+ */
+
export const useVolume = ({
mediaRef,
volume,
@@ -41,6 +66,12 @@ export const useVolume = ({
return;
}
+ // [1]
+ if (mediaRef.current.playbackRate !== 1 && isSafari()) {
+ warnSafariOnce(logLevel);
+ return;
+ }
+
if (!source) {
return;
}
@@ -58,7 +89,7 @@ export const useVolume = ({
Log.trace(
logLevel,
- `Starting to amplify ${mediaRef.current?.src}. Gain = ${currentVolumeRef.current}`,
+ `Starting to amplify ${mediaRef.current?.src}. Gain = ${currentVolumeRef.current}, playbackRate = ${mediaRef.current?.playbackRate}`,
);
return () => {
@@ -79,5 +110,15 @@ export const useVolume = ({
}
}
+ // [1]
+ if (
+ mediaRef.current &&
+ isSafari() &&
+ mediaRef.current?.playbackRate !== 1 &&
+ volume !== mediaRef.current?.volume
+ ) {
+ mediaRef.current.volume = Math.min(volume, 1);
+ }
+
return audioStuffRef;
};
diff --git a/packages/core/src/use-media-buffering.ts b/packages/core/src/use-media-buffering.ts
index eb4bca98de..437661b767 100644
--- a/packages/core/src/use-media-buffering.ts
+++ b/packages/core/src/use-media-buffering.ts
@@ -49,11 +49,13 @@ export const useMediaBuffering = ({
if (!navigator.userAgent.includes('Firefox/')) {
playbackLogging({
logLevel,
- message: `Calling .load() on ${current.src} because readyState is ${current.readyState} and it is not Firefox. Element is premounted`,
+ message: `Calling .load() on ${current.src} because readyState is ${current.readyState} and it is not Firefox. Element is premounted ${current.playbackRate}`,
tag: 'load',
mountTime,
});
+ const previousPlaybackRate = current.playbackRate;
current.load();
+ current.playbackRate = previousPlaybackRate;
}
}
@@ -147,12 +149,14 @@ export const useMediaBuffering = ({
if (!navigator.userAgent.includes('Firefox/')) {
playbackLogging({
logLevel,
- message: `Calling .load() on ${src} because readyState is ${current.readyState} and it is not Firefox.`,
+ message: `Calling .load() on ${src} because readyState is ${current.readyState} and it is not Firefox. ${current.playbackRate}`,
tag: 'load',
mountTime,
});
+ const previousPlaybackRate = current.playbackRate;
current.load();
+ current.playbackRate = previousPlaybackRate;
}
} else {
const onWaiting = () => {
diff --git a/packages/core/src/use-media-playback.ts b/packages/core/src/use-media-playback.ts
index 22f5e719e3..ade4bc109c 100644
--- a/packages/core/src/use-media-playback.ts
+++ b/packages/core/src/use-media-playback.ts
@@ -1,5 +1,11 @@
import type {RefObject} from 'react';
-import {useCallback, useContext, useEffect, useRef} from 'react';
+import {
+ useCallback,
+ useContext,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+} from 'react';
import {useMediaStartsAt} from './audio/use-audio-frame.js';
import {useBufferUntilFirstFrame} from './buffer-until-first-frame.js';
import {BufferingContextReact, useIsPlayerBuffering} from './buffering.js';
@@ -67,6 +73,10 @@ export const useMediaPlayback = ({
return;
}
+ if (isVariableFpsVideoMap.current[src]) {
+ return;
+ }
+
Log.verbose(
logLevel,
`Detected ${src} as a variable FPS video. Disabling buffering while seeking.`,
@@ -176,6 +186,19 @@ export const useMediaPlayback = ({
playing,
]);
+ // This must be a useLayoutEffect, because afterwards, useVolume() looks at the playbackRate
+ // and it is also in a useLayoutEffect.
+ useLayoutEffect(() => {
+ const playbackRateToSet = Math.max(0, playbackRate);
+ if (
+ mediaRef.current &&
+ mediaRef.current.playbackRate !== playbackRateToSet
+ ) {
+ console.log('setting playbackRate', playbackRateToSet);
+ mediaRef.current.playbackRate = playbackRateToSet;
+ }
+ }, [mediaRef, playbackRate]);
+
useEffect(() => {
const tagName = mediaType === 'audio' ? '<Audio>' : '<Video>';
if (!mediaRef.current) {
@@ -188,11 +211,6 @@ export const useMediaPlayback = ({
);
}
- const playbackRateToSet = Math.max(0, playbackRate);
- if (mediaRef.current.playbackRate !== playbackRateToSet) {
- mediaRef.current.playbackRate = playbackRateToSet;
- }
-
const {duration} = mediaRef.current;
const shouldBeTime =
!Number.isNaN(duration) && Number.isFinite(duration)
@@ -202,7 +220,7 @@ export const useMediaPlayback = ({
const mediaTagTime = mediaTagCurrentTime.current.time;
const rvcTime = rvcCurrentTime.current?.time ?? null;
- const isVariableFpsVideo = isVariableFpsVideoMap.current[src];
+ const isVariableFpsVideo = false;
const timeShiftMediaTag = Math.abs(shouldBeTime - mediaTagTime);
const timeShiftRvcTag = rvcTime ? Math.abs(shouldBeTime - rvcTime) : null;
diff --git a/packages/core/src/video/VideoForPreview.tsx b/packages/core/src/video/VideoForPreview.tsx
index 4fad6fa8d1..f0570b068d 100644
--- a/packages/core/src/video/VideoForPreview.tsx
+++ b/packages/core/src/video/VideoForPreview.tsx
@@ -129,13 +129,8 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<
isPremounting: Boolean(parentSequence?.premounting),
});
- useVolume({
- logLevel,
- mediaRef: videoRef,
- volume: userPreferredVolume,
- source: sharedSource,
- });
-
+ // putting playback before useVolume
+ // because volume looks at playbackrate
useMediaPlayback({
mediaRef: videoRef,
src,
@@ -148,6 +143,13 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<
onAutoPlayError: onAutoPlayError ?? null,
});
+ useVolume({
+ logLevel,
+ mediaRef: videoRef,
+ volume: userPreferredVolume,
+ source: sharedSource,
+ });
+
const actualFrom = parentSequence ? parentSequence.relativeFrom : 0;
const duration = parentSequence
? Math.min(parentSequence.durationInFrames, durationInFrames)
diff --git a/packages/core/src/video/video-fragment.ts b/packages/core/src/video/video-fragment.ts
index a757914383..31822da12f 100644
--- a/packages/core/src/video/video-fragment.ts
+++ b/packages/core/src/video/video-fragment.ts
@@ -4,15 +4,30 @@ const toSeconds = (time: number, fps: number) => {
return Math.round((time / fps) * 100) / 100;
};
+export const isSafari = () => {
+ if (typeof window === 'undefined') {
+ return false;
+ }
+
+ const isAppleWebKit = /AppleWebKit/.test(window.navigator.userAgent);
+
+ if (!isAppleWebKit) {
+ return false;
+ }
+
+ const isNotChrome = !window.navigator.userAgent.includes('Chrome/');
+
+ return isNotChrome;
+};
+
export const isIosSafari = () => {
if (typeof window === 'undefined') {
return false;
}
const isIpadIPodIPhone = /iP(ad|od|hone)/i.test(window.navigator.userAgent);
- const isAppleWebKit = /AppleWebKit/.test(window.navigator.userAgent);
- return isIpadIPodIPhone && isAppleWebKit;
+ return isIpadIPodIPhone && isSafari();
};
// https://github.com/remotion-dev/remotion/issues/1655
diff --git a/packages/docs/docs/audio.mdx b/packages/docs/docs/audio.mdx
index bd239d27d2..2b466c57ec 100644
--- a/packages/docs/docs/audio.mdx
+++ b/packages/docs/docs/audio.mdx
@@ -54,9 +54,17 @@ export const MyVideo = () => {
```
:::note
-On iOS Safari, it's currently not possible to granularly change the volume of a media tag.
-Before Remotion v4.0.279, the maximum value was 1.
-Since v4.0.279, the Web Audio API will be used to synthetically amplify audio that has a volume higher than 1.
+Since v4.0.302, it is now possible to:
+
+- Set the volume to a value higher than 1
+- In iOS Safari, set the volume to a value lower than 1
+
+Now arbitrary volumes are supported on all platforms, but there is 1 caveat on Safari:
+`volume` and `playbackRate` cannot be set at the same time, and if both are set,
+
+- on Desktop Safari, the volume will only be applied if it is 1 or lower
+- on iOS Safari, the volume will be ignored and set to 1
+
:::
### `loopVolumeCurveBehavior`<AvailableFrom v="4.0.142" />
diff --git a/packages/docs/docs/offthreadvideo.mdx b/packages/docs/docs/offthreadvideo.mdx
index 23944e5d99..cc7cb2ef47 100644
--- a/packages/docs/docs/offthreadvideo.mdx
+++ b/packages/docs/docs/offthreadvideo.mdx
@@ -112,9 +112,17 @@ export const MyComposition = () => {
```
:::note
-On iOS Safari, it's currently not possible to granularly change the volume of a media tag.
-Before Remotion v4.0.279, the maximum value was 1.
-Since v4.0.279, the Web Audio API will be used to synthetically amplify audio that has a volume higher than 1.
+Since v4.0.302, it is now possible to:
+
+- Set the volume to a value higher than 1
+- In iOS Safari, set the volume to a value lower than 1
+
+Now arbitrary volumes are supported on all platforms, but there is 1 caveat on Safari:
+`volume` and `playbackRate` cannot be set at the same time, and if both are set,
+
+- on Desktop Safari, the volume will only be applied if it is 1 or lower
+- on iOS Safari, the volume will be ignored and set to 1
+
:::
### `loopVolumeCurveBehavior?`<AvailableFrom v="4.0.142" />
diff --git a/packages/docs/docs/video.mdx b/packages/docs/docs/video.mdx
index e78b37a676..eca0ca2f78 100644
--- a/packages/docs/docs/video.mdx
+++ b/packages/docs/docs/video.mdx
@@ -127,9 +127,17 @@ export const MyComposition = () => {
```
:::note
-On iOS Safari, it's currently not possible to granularly change the volume of a media tag.
-Before Remotion v4.0.279, the maximum value was 1.
-Since v4.0.279, the Web Audio API will be used to synthetically amplify audio that has a volume higher than 1.
+Since v4.0.302, it is now possible to:
+
+- Set the volume to a value higher than 1
+- In iOS Safari, set the volume to a value lower than 1
+
+Now arbitrary volumes are supported on all platforms, but there is 1 caveat on Safari:
+`volume` and `playbackRate` cannot be set at the same time, and if both are set,
+
+- on Desktop Safari, the volume will only be applied if it is 1 or lower
+- on iOS Safari, the volume will be ignored and set to 1
+
:::
### `loopVolumeCurveBehavior?`<AvailableFrom v="4.0.142" />
diff --git a/packages/example/src/AudioTesting/Amplify.tsx b/packages/example/src/AudioTesting/Amplify.tsx
index b05ac28b49..86b521343e 100644
--- a/packages/example/src/AudioTesting/Amplify.tsx
+++ b/packages/example/src/AudioTesting/Amplify.tsx
@@ -66,6 +66,7 @@ const Amplify: React.FC = () => {
<OffthreadVideo
src={staticFile('vid1.mp4')}
volume={volume3}
+ playbackRate={2}
pauseWhenBuffering
style={{
height: 80,