Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Buffer audio based on duration (#9453)

Jonny Burgerb957e34e0fd1
diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.ts
index b33836b33f..74c8dd4b78 100644
--- a/packages/media/src/audio-iterator-manager.ts
+++ b/packages/media/src/audio-iterator-manager.ts
@@ -35,6 +35,12 @@ type ScheduleAudioNode = (
sourceDurationInSeconds: number,
) => ScheduleAudioNodeResult;
+export const MINIMUM_AUDIO_BUFFERING_TIME_SECONDS = 0.1;
+
+export const hasEnoughAudioToStartPlayback = (bufferedDuration: number) => {
+ return bufferedDuration >= MINIMUM_AUDIO_BUFFERING_TIME_SECONDS;
+};
+
export type AudioIteratorAnchor = {
// The unlooped time in seconds at which the current iterator was started
unloopedStartInSeconds: number;
@@ -292,7 +298,7 @@ export const audioIteratorManager = ({
) => number | null;
playbackRate: number;
scheduleAudioNode: ScheduleAudioNode;
- onScheduled: (mediaTimestamp: number) => void;
+ onScheduled: (sourceDurationInSeconds: number) => void;
onDone: () => void;
onDestroyed: () => void;
logLevel: LogLevel;
@@ -340,7 +346,7 @@ export const audioIteratorManager = ({
return;
}
- onScheduled(result.value.timelineTimestamp);
+ onScheduled(result.value.sourceDurationInSeconds);
notifyNodeScheduled();
onAudioChunk({
@@ -452,7 +458,16 @@ export const audioIteratorManager = ({
audioIteratorsCreated++;
audioBufferIterator = iterator;
- let chunksScheduled = 0;
+ let bufferedDuration = 0;
+ let hasUnblockedPlayback = false;
+ const unblockPlayback = () => {
+ if (hasUnblockedPlayback) {
+ return;
+ }
+
+ hasUnblockedPlayback = true;
+ delayHandle.unblock();
+ };
proceedScheduling({
iterator,
@@ -460,19 +475,22 @@ export const audioIteratorManager = ({
getTargetTime,
playbackRate,
scheduleAudioNode,
- onScheduled: () => {
- chunksScheduled++;
+ onScheduled: (sourceDurationInSeconds) => {
+ bufferedDuration += sourceDurationInSeconds;
// 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();
+ // otherwise we might be scheduling too late. This must be based on
+ // duration, not chunk count, because large PCM chunks can exceed the
+ // scheduling horizon before enough chunks are queued:
+ // https://github.com/remotion-dev/remotion/issues/9394
+ if (hasEnoughAudioToStartPlayback(bufferedDuration)) {
+ unblockPlayback();
}
},
onDestroyed: () => {
- delayHandle.unblock();
+ unblockPlayback();
},
onDone: () => {
- delayHandle.unblock();
+ unblockPlayback();
},
logLevel,
currentTime: sharedAudioContext.audioContext.currentTime,
diff --git a/packages/media/src/test/audio-iterator.test.ts b/packages/media/src/test/audio-iterator.test.ts
index c9bcd1e3e3..798fb043a9 100644
--- a/packages/media/src/test/audio-iterator.test.ts
+++ b/packages/media/src/test/audio-iterator.test.ts
@@ -4,10 +4,12 @@ import {expect, test} from 'vitest';
import {
anchorToContinuousTime,
audioIteratorManager,
+ hasEnoughAudioToStartPlayback,
} from '../audio-iterator-manager';
import {makeNonceManager} from '../nonce-manager';
const prepare = async (options?: {
+ src?: string;
fps?: number;
playbackRate?: number;
localPlaybackRate?: number;
@@ -18,6 +20,7 @@ const prepare = async (options?: {
loop?: boolean;
}) => {
const {
+ src = 'https://remotion.media/video.mp4',
fps = 30,
playbackRate = 1,
localPlaybackRate = playbackRate,
@@ -28,7 +31,7 @@ const prepare = async (options?: {
loop = false,
} = options ?? {};
const input = new Input({
- source: new UrlSource('https://remotion.media/video.mp4'),
+ source: new UrlSource(src),
formats: ALL_FORMATS,
});
const audioTrack = await input.getPrimaryAudioTrack();
@@ -51,11 +54,14 @@ const prepare = async (options?: {
const unscheduleAudioNode = () => {};
const audioSyncAnchor = {value: 0};
+ let playbackUnblocks = 0;
const manager = audioIteratorManager({
audioTrack,
delayPlaybackHandleIfNotPremounting: () => ({
- unblock: () => {},
+ unblock: () => {
+ playbackUnblocks++;
+ },
[Symbol.dispose]: () => {},
}),
sharedAudioContext: {
@@ -140,6 +146,7 @@ const prepare = async (options?: {
scheduledStartOffsets,
seek,
audioContextCurrentTime,
+ getPlaybackUnblocks: () => playbackUnblocks,
};
};
@@ -165,6 +172,27 @@ test('anchor maps unlooped time using the local playback rate', () => {
).toBe(8);
});
+test('audio startup buffering is based on duration instead of chunk count', () => {
+ expect(hasEnoughAudioToStartPlayback(0.099)).toBe(false);
+ expect(hasEnoughAudioToStartPlayback(0.1)).toBe(true);
+ expect(hasEnoughAudioToStartPlayback(0.5)).toBe(true);
+});
+
+test('PCM chunks unblock playback based on duration before six chunks or EOF', async () => {
+ const {manager, seek, scheduledChunks, getPlaybackUnblocks} = await prepare({
+ src: '/junk.wav',
+ });
+
+ seek({time: 0});
+ await manager.waitForNScheduledNodes(3);
+
+ expect(scheduledChunks).toEqual([
+ 0, 0.046439909297052155, 0.09287981859410431,
+ ]);
+ expect(getPlaybackUnblocks()).toBe(1);
+ manager.destroyIterator();
+});
+
test('media player should work', async () => {
const {manager, scheduledChunks, seek, audioContextCurrentTime} =
await prepare();