Skip to content

🎥 Make videos programmatically with React

`@remotion/player`: Smoother audio scheduling (#7305)

Jonny Burger694b10530d8c
diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsx
index ab1dbd049c..8757e69e4e 100644
--- a/packages/core/src/audio/shared-audio-tags.tsx
+++ b/packages/core/src/audio/shared-audio-tags.tsx
@@ -231,8 +231,11 @@ export const SharedAudioContextProvider: React.FC<{
throw new Error('Audio context not found');
}
+ const saveForLater =
+ ctxAndGain.audioContext.state === 'suspended' && !isResuming.current;
+
if (duration > 0) {
- if (ctxAndGain.audioContext.state === 'suspended') {
+ if (saveForLater) {
nodesToResume.current.set(node, {
scheduledTime,
offset,
@@ -264,7 +267,7 @@ export const SharedAudioContextProvider: React.FC<{
Log.verbose(
{logLevel, tag: 'audio-scheduling'},
- 'scheduled %c%s%c %s %c%s%c %s %c%s%c %s %s %s',
+ 'scheduled %c%s%c %s %c%s%c %s %c%s%c %s %s %s %s %s',
scheduledMismatch ? 'color: red; font-weight: bold' : '',
scheduledTime.toFixed(4),
'',
@@ -284,12 +287,15 @@ export const SharedAudioContextProvider: React.FC<{
(timeDiff < 0 ? ' delay' : ' ahead'),
'',
'current=' + currentTime.toFixed(4),
+ 'actualcurrent=' + ctxAndGain.audioContext.currentTime.toFixed(4),
'offset=' + offset.toFixed(4),
'latency=' + latency.toFixed(4),
'state=' + ctxAndGain.audioContext.state,
originalUnloopedMediaTimestamp !== mediaTime
? 'original_ts=' + originalUnloopedMediaTimestamp.toFixed(4)
: '',
+ 'action=' + (saveForLater ? 'schedule' : 'start'),
+ '',
);
prev.scheduledEndTime = scheduledEndTime;
@@ -318,6 +324,23 @@ export const SharedAudioContextProvider: React.FC<{
audioContextIsPlayingEventually.current = true;
+ ctxAndGain.gainNode.gain.cancelScheduledValues(
+ ctxAndGain.audioContext.currentTime,
+ );
+ ctxAndGain.gainNode.gain.setValueAtTime(
+ 0,
+ ctxAndGain.audioContext.currentTime,
+ );
+ ctxAndGain.gainNode.gain.linearRampToValueAtTime(
+ 1,
+ ctxAndGain.audioContext.currentTime + 0.03,
+ );
+
+ nodesToResume.current.forEach((r, node) => {
+ node.start(r.scheduledTime, r.offset, r.duration);
+ });
+ nodesToResume.current.clear();
+
const resumePromise = ctxAndGain.audioContext.resume();
isResuming.current = new Promise<void>((resolve) => {
@@ -334,23 +357,6 @@ export const SharedAudioContextProvider: React.FC<{
isResuming.current = null;
});
- ctxAndGain.gainNode.gain.cancelScheduledValues(
- ctxAndGain.audioContext.currentTime,
- );
- ctxAndGain.gainNode.gain.setValueAtTime(
- 0,
- ctxAndGain.audioContext.currentTime,
- );
- ctxAndGain.gainNode.gain.linearRampToValueAtTime(
- 1,
- ctxAndGain.audioContext.currentTime + 0.03,
- );
-
- nodesToResume.current.forEach((r, node) =>
- node.start(r.scheduledTime, r.offset, r.duration),
- );
- nodesToResume.current.clear();
-
return resumePromise.catch(() => {
// Already logged above; swallow to avoid unhandled rejection
// since callers (e.g. use-playback.ts) do not await this.
diff --git a/packages/example/src/AudioSmoothness/SlicedVideo.tsx b/packages/example/src/AudioSmoothness/SlicedVideo.tsx
index ab4fde3cf4..b73f7ecd59 100644
--- a/packages/example/src/AudioSmoothness/SlicedVideo.tsx
+++ b/packages/example/src/AudioSmoothness/SlicedVideo.tsx
@@ -1,10 +1,10 @@
-import {Video} from '@remotion/media';
+import {Audio} from '@remotion/media';
import React from 'react';
import {Composition, Sequence, useVideoConfig} from 'remotion';
const SLICE_DURATION_FRAMES = 6; // 0.1sec at 30fps
const NUM_SLICES = 100;
-const PREMOUNT_SEC = 0.5;
+const PREMOUNT_SEC = 1;
const SlicedVideo: React.FC = () => {
const src = 'https://remotion.media/video.mp4';
@@ -21,7 +21,7 @@ const SlicedVideo: React.FC = () => {
durationInFrames={SLICE_DURATION_FRAMES}
premountFor={PREMOUNT_SEC * fps}
>
- <Video src={src} trimBefore={from} debugOverlay />
+ <Audio src={src} trimBefore={from} />
</Sequence>
);
})}
diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.ts
index 467a454a9a..efc0440882 100644
--- a/packages/media/src/audio-iterator-manager.ts
+++ b/packages/media/src/audio-iterator-manager.ts
@@ -379,6 +379,8 @@ export const audioIteratorManager = ({
audioIteratorsCreated++;
audioBufferIterator = iterator;
+ let chunksScheduled = 0;
+
proceedScheduling({
iterator,
nonce,
@@ -386,7 +388,12 @@ export const audioIteratorManager = ({
playbackRate,
scheduleAudioNode,
onScheduled: () => {
- delayHandle.unblock();
+ chunksScheduled++;
+ // Need to schedule a bit into the future to unblock the buffer state,
+ // otherwise we might be scheduling too late.
+ if (chunksScheduled === 6) {
+ delayHandle.unblock();
+ }
},
onDestroyed: () => {
delayHandle.unblock();
diff --git a/packages/player/src/set-global-time-anchor.ts b/packages/player/src/set-global-time-anchor.ts
index 8034ceccf9..c0a5558b4b 100644
--- a/packages/player/src/set-global-time-anchor.ts
+++ b/packages/player/src/set-global-time-anchor.ts
@@ -8,12 +8,14 @@ export const setGlobalTimeAnchor = ({
absoluteTimeInSeconds,
globalPlaybackRate,
logLevel,
+ force,
}: {
audioContext: AudioContext;
audioSyncAnchor: {value: number};
absoluteTimeInSeconds: number;
globalPlaybackRate: number;
logLevel: LogLevel;
+ force: boolean;
}): boolean => {
const newAnchor =
audioContext.currentTime - absoluteTimeInSeconds / globalPlaybackRate;
@@ -23,13 +25,15 @@ export const setGlobalTimeAnchor = ({
const latency = audioContext.baseLatency + safeOutputLatency;
// Skip small shifts to avoid audio glitches from frame-quantized re-anchoring
- if (Math.abs(shift) < ALLOWED_GLOBAL_TIME_ANCHOR_SHIFT + latency) {
+ if (Math.abs(shift) < ALLOWED_GLOBAL_TIME_ANCHOR_SHIFT + latency && !force) {
return false;
}
Internals.Log.verbose(
{logLevel, tag: 'audio-scheduling'},
- 'Anchor changed from %s to %s with shift %s',
+ 'Anchor ' +
+ (force ? 'forcibly ' : '') +
+ 'changed from %s to %s with shift %s',
audioSyncAnchor.value,
newAnchor,
shift,
diff --git a/packages/player/src/use-playback.ts b/packages/player/src/use-playback.ts
index 6ff6752978..0161fe0d49 100644
--- a/packages/player/src/use-playback.ts
+++ b/packages/player/src/use-playback.ts
@@ -56,6 +56,8 @@ export const usePlayback = ({
videoConfig: config,
});
+ // Update time anchor when seeking:
+ // If the user clicked on a different time in the timeline, we need to re-sync the anchor
useLayoutEffect(() => {
if (!sharedAudioContext) {
return;
@@ -79,12 +81,55 @@ export const usePlayback = ({
absoluteTimeInSeconds: frame / config.fps,
globalPlaybackRate: playbackRate,
logLevel,
+ force: false,
});
if (changed) {
sharedAudioContext.audioSyncAnchorEmitter.dispatch('changed');
}
}, [config, frame, logLevel, playbackRate, sharedAudioContext, muted]);
+ // When the audio context is suspended, we use the opportunity to
+ // re-anchor the time to be exact.
+ useLayoutEffect(() => {
+ const audioContext = sharedAudioContext?.audioContext;
+ if (!audioContext) {
+ return;
+ }
+
+ if (!config) {
+ return;
+ }
+
+ if (muted) {
+ return;
+ }
+
+ const callback = () => {
+ if (audioContext.state !== 'running') {
+ setGlobalTimeAnchor({
+ audioContext,
+ audioSyncAnchor: sharedAudioContext.audioSyncAnchor,
+ absoluteTimeInSeconds: getCurrentFrame() / config.fps,
+ globalPlaybackRate: playbackRate,
+ logLevel,
+ force: true,
+ });
+ }
+ };
+
+ audioContext?.addEventListener('statechange', callback);
+ return () => {
+ audioContext?.removeEventListener('statechange', callback);
+ };
+ }, [
+ config,
+ getCurrentFrame,
+ logLevel,
+ muted,
+ playbackRate,
+ sharedAudioContext,
+ ]);
+
useEffect(() => {
if (!config) {
return;
@@ -135,11 +180,6 @@ export const usePlayback = ({
}
if (!muted && !context.buffering.current) {
- Internals.Log.trace(
- {logLevel, tag: 'audio'},
- 'Resuming audio context',
- sharedAudioContext?.audioContext?.currentTime,
- );
sharedAudioContext?.resume?.();
}
@@ -184,25 +224,6 @@ export const usePlayback = ({
sharedAudioContext?.getIsResumingAudioContext?.() ?? null;
if (getIsResumingAudioContext !== null && !muted) {
getIsResumingAudioContext.then(() => {
- if (!sharedAudioContext?.audioContext) {
- return;
- }
-
- if (!sharedAudioContext.audioSyncAnchor) {
- return;
- }
-
- // set it here and DON'T propagate an event
- // the useLayoutEffect above is supposed to handle a user seek,
- // this is a natural wait for the audio playback to start.
- // we don't wanna destroy the iterators.
- setGlobalTimeAnchor({
- audioContext: sharedAudioContext.audioContext,
- audioSyncAnchor: sharedAudioContext.audioSyncAnchor,
- absoluteTimeInSeconds: getCurrentFrame() / config.fps,
- globalPlaybackRate: playbackRate,
- logLevel,
- });
startedTime = performance.now();
framesAdvanced = 0;
queueNextFrame();