Skip to content

🎥 Make videos programmatically with React

encapsulate audio iterator

JonnyBurger500e213292c3
diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.ts
new file mode 100644
index 0000000000..f148b6f583
--- /dev/null
+++ b/packages/media/src/audio-iterator-manager.ts
@@ -0,0 +1,77 @@
+import type {InputAudioTrack} from 'mediabunny';
+import {AudioBufferSink} from 'mediabunny';
+import type {useBufferState} from 'remotion';
+import type {AudioIterator} from './audio/audio-preview-iterator';
+import {makeAudioIterator} from './audio/audio-preview-iterator';
+
+export const audioIteratorManager = (
+ audioTrack: InputAudioTrack,
+ bufferState: ReturnType<typeof useBufferState>,
+) => {
+ let audioChunksForAfterResuming: {
+ buffer: AudioBuffer;
+ timestamp: number;
+ }[] = [];
+
+ const audioSink = new AudioBufferSink(audioTrack);
+ let audioBufferIterator: AudioIterator | null = null;
+ let audioIteratorsCreated = 0;
+
+ const startAudioIterator = async (
+ startFromSecond: number,
+ nonce: number,
+ getSeekNonce: () => number,
+ ) => {
+ audioBufferIterator?.destroy();
+ audioChunksForAfterResuming = [];
+ const delayHandle = bufferState.delayPlayback();
+
+ const iterator = makeAudioIterator(audioSink, startFromSecond);
+ audioIteratorsCreated++;
+ audioBufferIterator = iterator;
+
+ // Schedule up to 3 buffers ahead of the current time
+ for (let i = 0; i < 3; i++) {
+ const result = await iterator.getNext();
+
+ if (iterator.isDestroyed()) {
+ delayHandle.unblock();
+ return;
+ }
+
+ if (nonce !== getSeekNonce()) {
+ delayHandle.unblock();
+ return;
+ }
+
+ if (!result.value) {
+ // media ended
+ delayHandle.unblock();
+ return;
+ }
+
+ const {buffer, timestamp} = result.value;
+
+ audioChunksForAfterResuming.push({
+ buffer,
+ timestamp,
+ });
+ }
+
+ delayHandle.unblock();
+ };
+
+ return {
+ startAudioIterator,
+ getAudioChunksForAfterResuming: () => audioChunksForAfterResuming,
+ getAudioBufferIterator: () => audioBufferIterator,
+ destroy: () => {
+ audioBufferIterator?.destroy();
+ audioBufferIterator = null;
+ audioChunksForAfterResuming.length = 0;
+ },
+ getAudioIteratorsCreated: () => audioIteratorsCreated,
+ };
+};
+
+export type AudioIteratorManager = ReturnType<typeof audioIteratorManager>;
diff --git a/packages/media/src/debug-overlay/preview-overlay.ts b/packages/media/src/debug-overlay/preview-overlay.ts
index 6694dd76f9..df6ebae9f3 100644
--- a/packages/media/src/debug-overlay/preview-overlay.ts
+++ b/packages/media/src/debug-overlay/preview-overlay.ts
@@ -1,8 +1,7 @@
-import type {AudioIterator} from '../audio/audio-preview-iterator';
+import type {AudioIteratorManager} from '../audio-iterator-manager';
export type DebugStats = {
videoIteratorsCreated: number;
- audioIteratorsCreated: number;
framesRendered: number;
};
@@ -11,42 +10,42 @@ export const drawPreviewOverlay = ({
stats,
audioTime,
audioContextState,
- audioIterator,
audioSyncAnchor,
- audioChunksForAfterResuming,
playing,
+ audioIteratorManager,
}: {
context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;
stats: DebugStats;
audioTime: number;
audioContextState: AudioContextState;
audioSyncAnchor: number;
- audioIterator: AudioIterator | null;
- audioChunksForAfterResuming: {
- buffer: AudioBuffer;
- timestamp: number;
- }[];
playing: boolean;
+ audioIteratorManager: AudioIteratorManager | null;
}) => {
// Collect all lines to be rendered
const lines: string[] = [
'Debug overlay',
`Video iterators created: ${stats.videoIteratorsCreated}`,
- `Audio iterators created: ${stats.audioIteratorsCreated}`,
+ `Audio iterators created: ${audioIteratorManager?.getAudioIteratorsCreated()}`,
`Frames rendered: ${stats.framesRendered}`,
`Audio context state: ${audioContextState}`,
`Audio time: ${(audioTime - audioSyncAnchor).toFixed(3)}s`,
];
- if (audioIterator) {
- const queuedPeriod = audioIterator.getQueuedPeriod();
+ if (audioIteratorManager) {
+ const queuedPeriod = audioIteratorManager
+ .getAudioBufferIterator()
+ ?.getQueuedPeriod();
if (queuedPeriod) {
lines.push(
`Audio queued until: ${(queuedPeriod.until - (audioTime - audioSyncAnchor)).toFixed(3)}s`,
);
- } else if (audioChunksForAfterResuming.length > 0) {
+ } else if (
+ audioIteratorManager?.getAudioChunksForAfterResuming()?.length &&
+ audioIteratorManager?.getAudioChunksForAfterResuming()?.length > 0
+ ) {
lines.push(
- `Audio chunks for after resuming: ${audioChunksForAfterResuming.length}`,
+ `Audio chunks for after resuming: ${audioIteratorManager?.getAudioChunksForAfterResuming()?.length}`,
);
}
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index 492908ee67..b20863677d 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -1,18 +1,12 @@
import type {WrappedAudioBuffer, WrappedCanvas} from 'mediabunny';
-import {
- ALL_FORMATS,
- AudioBufferSink,
- CanvasSink,
- Input,
- UrlSource,
-} from 'mediabunny';
+import {ALL_FORMATS, CanvasSink, Input, UrlSource} from 'mediabunny';
import type {LogLevel, useBufferState} from 'remotion';
import {Internals} from 'remotion';
import {
- isAlreadyQueued,
- makeAudioIterator,
- type AudioIterator,
-} from './audio/audio-preview-iterator';
+ audioIteratorManager,
+ type AudioIteratorManager,
+} from './audio-iterator-manager';
+import {isAlreadyQueued} from './audio/audio-preview-iterator';
import type {DebugStats} from './debug-overlay/preview-overlay';
import {drawPreviewOverlay} from './debug-overlay/preview-overlay';
import {getTimeInSeconds} from './get-time-in-seconds';
@@ -46,18 +40,16 @@ export class MediaPlayer {
private videoFrameIterator: VideoIterator | null = null;
debugStats: DebugStats = {
videoIteratorsCreated: 0,
- audioIteratorsCreated: 0,
framesRendered: 0,
};
- private audioSink: AudioBufferSink | null = null;
- private audioBufferIterator: AudioIterator | null = null;
-
private gainNode: GainNode | null = null;
private currentVolume: number = 1;
private sharedAudioContext: AudioContext;
+ private audioIteratorManager: AudioIteratorManager | null = null;
+
// this is the time difference between Web Audio timeline
// and media file timeline
private audioSyncAnchor: number = 0;
@@ -147,10 +139,6 @@ export class MediaPlayer {
);
}
- private hasAudio(): boolean {
- return Boolean(this.audioSink && this.sharedAudioContext && this.gainNode);
- }
-
private isDisposalError(): boolean {
return this.input?.disposed === true;
}
@@ -233,7 +221,10 @@ export class MediaPlayer {
}
if (audioTrack && this.sharedAudioContext) {
- this.audioSink = new AudioBufferSink(audioTrack);
+ this.audioIteratorManager = audioIteratorManager(
+ audioTrack,
+ this.bufferState,
+ );
this.gainNode = this.sharedAudioContext.createGain();
this.gainNode.connect(this.sharedAudioContext.destination);
}
@@ -263,7 +254,14 @@ export class MediaPlayer {
try {
// intentionally not awaited
- this.startAudioIterator(startTime, this.currentSeekNonce);
+ if (this.audioIteratorManager) {
+ this.audioIteratorManager.startAudioIterator(
+ startTime,
+ this.currentSeekNonce,
+ () => this.currentSeekNonce,
+ );
+ }
+
await this.startVideoIterator(startTime, this.currentSeekNonce);
} catch (error) {
if (this.isDisposalError()) {
@@ -345,8 +343,7 @@ export class MediaPlayer {
this.videoFrameIterator = null;
this.clearCanvas();
- this.audioBufferIterator?.destroy();
- this.audioBufferIterator = null;
+ this.audioIteratorManager?.getAudioBufferIterator()?.destroy();
return;
}
@@ -372,14 +369,17 @@ export class MediaPlayer {
this.startVideoIterator(newTime, nonce);
}
- const queuedPeriod = this.audioBufferIterator?.getQueuedPeriod();
+ const queuedPeriod = this.audioIteratorManager
+ ?.getAudioBufferIterator()
+ ?.getQueuedPeriod();
const currentTimeIsAlreadyQueued = isAlreadyQueued(newTime, queuedPeriod);
const toBeScheduled: WrappedAudioBuffer[] = [];
if (!currentTimeIsAlreadyQueued) {
- const audioSatisfyResult =
- await this.audioBufferIterator?.tryToSatisfySeek(newTime);
+ const audioSatisfyResult = await this.audioIteratorManager
+ ?.getAudioBufferIterator()
+ ?.tryToSatisfySeek(newTime);
if (this.currentSeekNonce !== nonce) {
return;
@@ -390,7 +390,14 @@ export class MediaPlayer {
}
if (audioSatisfyResult.type === 'not-satisfied') {
- await this.startAudioIterator(newTime, nonce);
+ if (this.audioIteratorManager) {
+ await this.audioIteratorManager.startAudioIterator(
+ newTime,
+ nonce,
+ () => this.currentSeekNonce,
+ );
+ }
+
return;
}
@@ -406,8 +413,9 @@ export class MediaPlayer {
(1 / this.fps) * this.playbackRate;
const nextIsAlreadyQueued = isAlreadyQueued(nextTime, queuedPeriod);
if (!nextIsAlreadyQueued) {
- const audioSatisfyResult =
- await this.audioBufferIterator?.tryToSatisfySeek(nextTime);
+ const audioSatisfyResult = await this.audioIteratorManager
+ ?.getAudioBufferIterator()
+ ?.tryToSatisfySeek(nextTime);
if (this.currentSeekNonce !== nonce) {
return;
@@ -418,7 +426,14 @@ export class MediaPlayer {
}
if (audioSatisfyResult.type === 'not-satisfied') {
- await this.startAudioIterator(nextTime, nonce);
+ if (this.audioIteratorManager) {
+ await this.audioIteratorManager.startAudioIterator(
+ nextTime,
+ nonce,
+ () => this.currentSeekNonce,
+ );
+ }
+
return;
}
@@ -428,8 +443,8 @@ export class MediaPlayer {
for (const buffer of toBeScheduled) {
if (this.playing) {
this.scheduleAudioChunk(buffer.buffer, buffer.timestamp);
- } else {
- this.audioChunksForAfterResuming.push({
+ } else if (this.audioIteratorManager) {
+ this.audioIteratorManager.getAudioChunksForAfterResuming().push({
buffer: buffer.buffer,
timestamp: buffer.timestamp,
});
@@ -443,26 +458,32 @@ export class MediaPlayer {
this.setPlaybackTime(time);
this.playing = true;
- for (const chunk of this.audioChunksForAfterResuming) {
- this.scheduleAudioChunk(chunk.buffer, chunk.timestamp);
+ if (this.audioIteratorManager) {
+ for (const chunk of this.audioIteratorManager.getAudioChunksForAfterResuming()) {
+ this.scheduleAudioChunk(chunk.buffer, chunk.timestamp);
+ }
}
if (this.sharedAudioContext.state === 'suspended') {
await this.sharedAudioContext.resume();
}
- this.audioChunksForAfterResuming.length = 0;
+ if (this.audioIteratorManager) {
+ this.audioIteratorManager.getAudioChunksForAfterResuming().length = 0;
+ }
+
this.drawDebugOverlay();
}
public pause(): void {
this.playing = false;
- const toQueue =
- this.audioBufferIterator?.removeAndReturnAllQueuedAudioNodes();
+ const toQueue = this.audioIteratorManager
+ ?.getAudioBufferIterator()
+ ?.removeAndReturnAllQueuedAudioNodes();
- if (toQueue) {
+ if (toQueue && this.audioIteratorManager) {
for (const chunk of toQueue) {
- this.audioChunksForAfterResuming.push({
+ this.audioIteratorManager.getAudioChunksForAfterResuming().push({
buffer: chunk.buffer,
timestamp: chunk.timestamp,
});
@@ -524,8 +545,7 @@ export class MediaPlayer {
this.input?.dispose();
this.videoFrameIterator?.destroy();
this.videoFrameIterator = null;
- this.audioBufferIterator?.destroy();
- this.audioBufferIterator = null;
+ this.audioIteratorManager?.getAudioBufferIterator()?.destroy();
}
private getPlaybackTime(): number {
@@ -536,11 +556,6 @@ export class MediaPlayer {
this.audioSyncAnchor = this.sharedAudioContext.currentTime - time;
}
- private audioChunksForAfterResuming: {
- buffer: AudioBuffer;
- timestamp: number;
- }[] = [];
-
private scheduleAudioChunk(
buffer: AudioBuffer,
mediaTimestamp: number,
@@ -563,9 +578,13 @@ export class MediaPlayer {
node.start(this.sharedAudioContext.currentTime, -delay);
}
- this.audioBufferIterator!.addQueuedAudioNode(node, mediaTimestamp, buffer);
+ this.audioIteratorManager
+ ?.getAudioBufferIterator()!
+ .addQueuedAudioNode(node, mediaTimestamp, buffer);
node.onended = () => {
- return this.audioBufferIterator!.removeQueuedAudioNode(node);
+ return this.audioIteratorManager
+ ?.getAudioBufferIterator()!
+ .removeQueuedAudioNode(node);
};
}
@@ -605,51 +624,6 @@ export class MediaPlayer {
);
};
- private startAudioIterator = async (
- startFromSecond: number,
- nonce: number,
- ): Promise<void> => {
- if (!this.hasAudio()) return;
-
- this.audioBufferIterator?.destroy();
- this.audioChunksForAfterResuming = [];
- const delayHandle = this.bufferState.delayPlayback();
-
- const iterator = makeAudioIterator(this.audioSink!, startFromSecond);
- this.debugStats.audioIteratorsCreated++;
- this.audioBufferIterator = iterator;
-
- // Schedule up to 3 buffers ahead of the current time
- for (let i = 0; i < 3; i++) {
- const result = await iterator.getNext();
-
- if (iterator.isDestroyed()) {
- delayHandle.unblock();
- return;
- }
-
- if (nonce !== this.currentSeekNonce) {
- delayHandle.unblock();
- return;
- }
-
- if (!result.value) {
- // media ended
- delayHandle.unblock();
- return;
- }
-
- const {buffer, timestamp} = result.value;
-
- this.audioChunksForAfterResuming.push({
- buffer,
- timestamp,
- });
- }
-
- delayHandle.unblock();
- };
-
private drawDebugOverlay(): void {
if (!this.debugOverlay) return;
if (this.context && this.canvas) {
@@ -659,8 +633,7 @@ export class MediaPlayer {
audioTime: this.sharedAudioContext.currentTime,
audioContextState: this.sharedAudioContext.state,
audioSyncAnchor: this.audioSyncAnchor,
- audioIterator: this.audioBufferIterator,
- audioChunksForAfterResuming: this.audioChunksForAfterResuming,
+ audioIteratorManager: this.audioIteratorManager,
playing: this.playing,
});
}
diff --git a/packages/media/src/test/media-player.test.ts b/packages/media/src/test/media-player.test.ts
index 723a7ed253..e949f975d7 100644
--- a/packages/media/src/test/media-player.test.ts
+++ b/packages/media/src/test/media-player.test.ts
@@ -22,7 +22,6 @@ test('media player should work', async () => {
});
await mediaPlayer.initialize(0);
expect(mediaPlayer.debugStats).toEqual({
- audioIteratorsCreated: 1,
framesRendered: 1,
videoIteratorsCreated: 1,
});