Skip to content

🎥 Make videos programmatically with React

set amplification

Jonny Burger5d8031eaa7b5
diff --git a/packages/core/src/audio/AudioForPreview.tsx b/packages/core/src/audio/AudioForPreview.tsx
index cadfc8aca6..e5d30a1841 100644
--- a/packages/core/src/audio/AudioForPreview.tsx
+++ b/packages/core/src/audio/AudioForPreview.tsx
@@ -14,10 +14,7 @@ import {usePreload} from '../prefetch.js';
import {random} from '../random.js';
import {useAmplification} from '../use-amplification.js';
import {useMediaInTimeline} from '../use-media-in-timeline.js';
-import {
- DEFAULT_ACCEPTABLE_TIMESHIFT,
- useMediaPlayback,
-} from '../use-media-playback.js';
+import {useMediaPlayback} from '../use-media-playback.js';
import {useSyncVolumeWithMediaTag} from '../use-sync-volume-with-media-tag.js';
import {
useMediaMutedState,
@@ -161,23 +158,23 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<
isPremounting: Boolean(sequenceContext?.premounting),
});
+ useAmplification({
+ logLevel,
+ mediaRef: audioRef,
+ volume: userPreferredVolume,
+ });
+
useMediaPlayback({
mediaRef: audioRef,
src,
mediaType: 'audio',
playbackRate: playbackRate ?? 1,
onlyWarnForMediaSeekingError: false,
- acceptableTimeshift:
- acceptableTimeShiftInSeconds ?? DEFAULT_ACCEPTABLE_TIMESHIFT,
+ acceptableTimeshift: acceptableTimeShiftInSeconds ?? null,
isPremounting: Boolean(sequenceContext?.premounting),
pauseWhenBuffering,
onAutoPlayError: null,
- });
-
- useAmplification({
- logLevel,
- mediaRef: audioRef,
- volume: userPreferredVolume,
+ userPreferredVolume,
});
useImperativeHandle(ref, () => {
diff --git a/packages/core/src/use-amplification.ts b/packages/core/src/use-amplification.ts
index 7247fa9717..5267493e5b 100644
--- a/packages/core/src/use-amplification.ts
+++ b/packages/core/src/use-amplification.ts
@@ -1,4 +1,4 @@
-import {useEffect, useLayoutEffect, useRef, type RefObject} from 'react';
+import {useLayoutEffect, useRef, type RefObject} from 'react';
import type {LogLevel} from './log';
import {Log} from './log';
@@ -20,6 +20,10 @@ type AudioItems = {
audioContext: AudioContext;
};
+export const getShouldAmplify = (volume: number) => {
+ return volume > 1;
+};
+
export const useAmplification = ({
mediaRef,
volume,
@@ -29,8 +33,10 @@ export const useAmplification = ({
volume: number;
logLevel: LogLevel;
}) => {
- const shouldAmplify = volume > 1;
+ const shouldAmplify = getShouldAmplify(volume);
const audioStuffRef = useRef<AudioItems | null>(null);
+ const currentVolumeRef = useRef(volume);
+ currentVolumeRef.current = volume;
useLayoutEffect(() => {
if (!shouldAmplify) {
@@ -50,34 +56,42 @@ export const useAmplification = ({
return;
}
- const audioContext = new AudioContext();
- const source = audioContext.createMediaElementSource(mediaRef.current);
- const gainNode = audioContext.createGain();
+ const audioContext = new AudioContext({
+ latencyHint: 'interactive',
+ });
+
+ const source = new MediaElementAudioSourceNode(audioContext, {
+ mediaElement: mediaRef.current,
+ });
+
+ const gainNode = new GainNode(audioContext, {
+ gain: currentVolumeRef.current,
+ });
audioStuffRef.current = {
gainNode,
source,
audioContext,
};
+
source.connect(gainNode);
gainNode.connect(audioContext.destination);
+ Log.trace(
+ logLevel,
+ `Starting to amplify ${mediaRef.current?.src}. Gain = ${currentVolumeRef.current}`,
+ );
}, [logLevel, mediaRef, shouldAmplify]);
- useLayoutEffect(() => {
- if (!audioStuffRef.current) {
- return;
- }
-
- if (volume <= 1) {
- audioStuffRef.current.gainNode.gain.value = 1;
+ if (audioStuffRef.current) {
+ const valueToSet = Math.max(volume, 1);
+ if (audioStuffRef.current.gainNode.gain.value !== valueToSet) {
+ audioStuffRef.current.gainNode.gain.value = valueToSet;
+ Log.trace(
+ logLevel,
+ `Setting gain to ${valueToSet} for ${mediaRef.current?.src}`,
+ );
}
+ }
- audioStuffRef.current.gainNode.gain.value = volume;
- }, [volume]);
-
- useEffect(() => {
- return () => {
- audioStuffRef.current = null;
- };
- }, []);
+ return audioStuffRef;
};
diff --git a/packages/core/src/use-media-playback.ts b/packages/core/src/use-media-playback.ts
index 5d703aab40..d8bf1a03a8 100644
--- a/packages/core/src/use-media-playback.ts
+++ b/packages/core/src/use-media-playback.ts
@@ -13,6 +13,7 @@ import {
usePlayingState,
useTimelinePosition,
} from './timeline-position-state.js';
+import {getShouldAmplify} from './use-amplification.js';
import {useCurrentFrame} from './use-current-frame.js';
import {useMediaBuffering} from './use-media-buffering.js';
import {useRequestVideoCallbackTime} from './use-request-video-callback-time.js';
@@ -20,8 +21,6 @@ import {useVideoConfig} from './use-video-config.js';
import {getMediaTime} from './video/get-current-time.js';
import {warnAboutNonSeekableMedia} from './warn-about-non-seekable-media.js';
-export const DEFAULT_ACCEPTABLE_TIMESHIFT = 0.45;
-
export const useMediaPlayback = ({
mediaRef,
src,
@@ -32,16 +31,18 @@ export const useMediaPlayback = ({
pauseWhenBuffering,
isPremounting,
onAutoPlayError,
+ userPreferredVolume,
}: {
mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement | null>;
src: string | undefined;
mediaType: 'audio' | 'video';
playbackRate: number;
onlyWarnForMediaSeekingError: boolean;
- acceptableTimeshift: number;
+ acceptableTimeshift: number | null;
pauseWhenBuffering: boolean;
isPremounting: boolean;
onAutoPlayError: null | (() => void);
+ userPreferredVolume: number;
}) => {
const {playbackRate: globalPlaybackRate} = useContext(TimelineContext);
const frame = useCurrentFrame();
@@ -109,16 +110,26 @@ export const useMediaPlayback = ({
const playbackRate = localPlaybackRate * globalPlaybackRate;
- // For short audio, a lower acceptable time shift is used
const acceptableTimeShiftButLessThanDuration = (() => {
+ // In Safari, it seems to lag behind mostly around ~0.4 seconds
+ const DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_NORMAL_PLAYBACK = 0.45;
+
+ // If there is amplification, the acceptable timeshift is higher
+ const DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_AMPLIFICATION =
+ DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_NORMAL_PLAYBACK + 0.2;
+
+ const defaultAcceptableTimeshift = getShouldAmplify(userPreferredVolume)
+ ? DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_AMPLIFICATION
+ : DEFAULT_ACCEPTABLE_TIMESHIFT_WITH_NORMAL_PLAYBACK;
+ // For short audio, a lower acceptable time shift is used
if (mediaRef.current?.duration) {
return Math.min(
mediaRef.current.duration,
- acceptableTimeshift ?? DEFAULT_ACCEPTABLE_TIMESHIFT,
+ acceptableTimeshift ?? defaultAcceptableTimeshift,
);
}
- return acceptableTimeshift;
+ return acceptableTimeshift ?? defaultAcceptableTimeshift;
})();
const isPlayerBuffering = useIsPlayerBuffering(buffering);
@@ -240,7 +251,7 @@ export const useMediaPlayback = ({
return;
}
- const seekThreshold = playing ? 0.15 : 0.00001;
+ const seekThreshold = playing ? 0.15 : 0.01;
// Only perform a seek if the time is not already the same.
// Chrome rounds to 6 digits, so 0.033333333 -> 0.033333,
diff --git a/packages/core/src/video/VideoForPreview.tsx b/packages/core/src/video/VideoForPreview.tsx
index 139790587a..b0254ad46c 100644
--- a/packages/core/src/video/VideoForPreview.tsx
+++ b/packages/core/src/video/VideoForPreview.tsx
@@ -15,10 +15,7 @@ import {playbackLogging} from '../playback-logging.js';
import {usePreload} from '../prefetch.js';
import {useAmplification} from '../use-amplification.js';
import {useMediaInTimeline} from '../use-media-in-timeline.js';
-import {
- DEFAULT_ACCEPTABLE_TIMESHIFT,
- useMediaPlayback,
-} from '../use-media-playback.js';
+import {useMediaPlayback} from '../use-media-playback.js';
import {useSyncVolumeWithMediaTag} from '../use-sync-volume-with-media-tag.js';
import {useVideoConfig} from '../use-video-config.js';
import {
@@ -134,11 +131,11 @@ const VideoForDevelopmentRefForwardingFunction: React.ForwardRefRenderFunction<
mediaType: 'video',
playbackRate: props.playbackRate ?? 1,
onlyWarnForMediaSeekingError,
- acceptableTimeshift:
- acceptableTimeShiftInSeconds ?? DEFAULT_ACCEPTABLE_TIMESHIFT,
+ acceptableTimeshift: acceptableTimeShiftInSeconds ?? null,
isPremounting: Boolean(parentSequence?.premounting),
pauseWhenBuffering,
onAutoPlayError: onAutoPlayError ?? null,
+ userPreferredVolume,
});
const actualFrom = parentSequence ? parentSequence.relativeFrom : 0;