Skip to content

🎥 Make videos programmatically with React

encapsulate audio iterator

JonnyBurger1d86e6e5ce92
diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.ts
index 2838420c24..9d260e4f21 100644
--- a/packages/media/src/audio-iterator-manager.ts
+++ b/packages/media/src/audio-iterator-manager.ts
@@ -1,20 +1,30 @@
-import type {InputAudioTrack} from 'mediabunny';
+import type {InputAudioTrack, WrappedAudioBuffer} 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';
+import {
+ isAlreadyQueued,
+ makeAudioIterator,
+} from './audio/audio-preview-iterator';
export const audioIteratorManager = ({
audioTrack,
bufferState,
+ sharedAudioContext,
}: {
audioTrack: InputAudioTrack;
bufferState: ReturnType<typeof useBufferState>;
+ sharedAudioContext: AudioContext;
}) => {
+ let muted = false;
+ let currentVolume = 1;
+
let audioChunksForAfterResuming: {
buffer: AudioBuffer;
timestamp: number;
}[] = [];
+ const gainNode = sharedAudioContext.createGain();
+ gainNode.connect(sharedAudioContext.destination);
const audioSink = new AudioBufferSink(audioTrack);
let audioBufferIterator: AudioIterator | null = null;
@@ -64,16 +74,210 @@ export const audioIteratorManager = ({
delayHandle.unblock();
};
+ const scheduleAudioChunk = ({
+ buffer,
+ mediaTimestamp,
+ trimBefore,
+ fps,
+ playbackRate,
+ audioSyncAnchor,
+ }: {
+ buffer: AudioBuffer;
+ mediaTimestamp: number;
+ trimBefore: number | undefined;
+ fps: number;
+ playbackRate: number;
+ audioSyncAnchor: number;
+ }) => {
+ // TODO: Might already be scheduled, and then the playback rate changes
+ // TODO: Playbackrate does not yet work
+ const targetTime =
+ (mediaTimestamp - (trimBefore ?? 0) / fps) / playbackRate;
+ const delay = targetTime + audioSyncAnchor - sharedAudioContext.currentTime;
+
+ const node = sharedAudioContext.createBufferSource();
+ node.buffer = buffer;
+ node.playbackRate.value = playbackRate;
+ node.connect(gainNode);
+
+ if (delay >= 0) {
+ node.start(targetTime + audioSyncAnchor);
+ } else {
+ node.start(sharedAudioContext.currentTime, -delay);
+ }
+
+ if (!audioBufferIterator) {
+ throw new Error('Audio buffer iterator not found');
+ }
+
+ audioBufferIterator.addQueuedAudioNode(node, mediaTimestamp, buffer);
+ node.onended = () => {
+ if (!audioBufferIterator) {
+ throw new Error('Audio buffer iterator not found');
+ }
+
+ return audioBufferIterator.removeQueuedAudioNode(node);
+ };
+ };
+
+ const pausePlayback = () => {
+ if (!audioBufferIterator) {
+ return;
+ }
+
+ const toQueue = audioBufferIterator.removeAndReturnAllQueuedAudioNodes();
+ for (const chunk of toQueue) {
+ audioChunksForAfterResuming.push({
+ buffer: chunk.buffer,
+ timestamp: chunk.timestamp,
+ });
+ }
+ };
+
+ const seek = async ({
+ newTime,
+ nonce,
+ getSeekNonce,
+ fps,
+ playbackRate,
+ audioSyncAnchor,
+ trimBefore,
+ getIsPlaying,
+ }: {
+ newTime: number;
+ nonce: number;
+ getSeekNonce: () => number;
+ fps: number;
+ playbackRate: number;
+ audioSyncAnchor: number;
+ trimBefore: number | undefined;
+ getIsPlaying: () => boolean;
+ }) => {
+ if (!audioBufferIterator) {
+ throw new Error('Audio buffer iterator not found');
+ }
+
+ const queuedPeriod = audioBufferIterator.getQueuedPeriod();
+
+ const currentTimeIsAlreadyQueued = isAlreadyQueued(newTime, queuedPeriod);
+ const toBeScheduled: WrappedAudioBuffer[] = [];
+
+ if (!currentTimeIsAlreadyQueued) {
+ const audioSatisfyResult =
+ await audioBufferIterator.tryToSatisfySeek(newTime);
+
+ if (getSeekNonce() !== nonce) {
+ return;
+ }
+
+ if (!audioSatisfyResult) {
+ return;
+ }
+
+ if (audioSatisfyResult.type === 'not-satisfied') {
+ await startAudioIterator(newTime, nonce, getSeekNonce);
+
+ return;
+ }
+
+ toBeScheduled.push(...audioSatisfyResult.buffers);
+ }
+
+ // TODO: What is this is beyond the end of the video
+ const nextTime =
+ newTime +
+ // start of next frame
+ (1 / fps) * playbackRate +
+ // need the full duration of the next frame to be queued
+ (1 / fps) * playbackRate;
+ const nextIsAlreadyQueued = isAlreadyQueued(nextTime, queuedPeriod);
+ if (!nextIsAlreadyQueued) {
+ const audioSatisfyResult =
+ await audioBufferIterator.tryToSatisfySeek(nextTime);
+
+ if (getSeekNonce() !== nonce) {
+ return;
+ }
+
+ if (!audioSatisfyResult) {
+ return;
+ }
+
+ if (audioSatisfyResult.type === 'not-satisfied') {
+ await startAudioIterator(nextTime, nonce, getSeekNonce);
+
+ return;
+ }
+
+ toBeScheduled.push(...audioSatisfyResult.buffers);
+ }
+
+ for (const buffer of toBeScheduled) {
+ if (getIsPlaying()) {
+ scheduleAudioChunk({
+ buffer: buffer.buffer,
+ mediaTimestamp: buffer.timestamp,
+ trimBefore,
+ fps,
+ playbackRate,
+ audioSyncAnchor,
+ });
+ } else {
+ audioChunksForAfterResuming.push({
+ buffer: buffer.buffer,
+ timestamp: buffer.timestamp,
+ });
+ }
+ }
+ };
+
+ const resumePlayback = ({
+ audioSyncAnchor,
+ fps,
+ playbackRate,
+ trimBefore,
+ }: {
+ trimBefore: number | undefined;
+ fps: number;
+ playbackRate: number;
+ audioSyncAnchor: number;
+ }) => {
+ for (const chunk of audioChunksForAfterResuming) {
+ scheduleAudioChunk({
+ buffer: chunk.buffer,
+ mediaTimestamp: chunk.timestamp,
+ trimBefore,
+ fps,
+ playbackRate,
+ audioSyncAnchor,
+ });
+ }
+
+ audioChunksForAfterResuming = [];
+ };
+
return {
startAudioIterator,
- getAudioChunksForAfterResuming: () => audioChunksForAfterResuming,
+ resumeScheduledAudioChunks: resumePlayback,
+ pausePlayback,
getAudioBufferIterator: () => audioBufferIterator,
+ getNumberOfChunksAfterResuming: () => audioChunksForAfterResuming.length,
destroy: () => {
audioBufferIterator?.destroy();
audioBufferIterator = null;
audioChunksForAfterResuming = [];
},
+ seek,
getAudioIteratorsCreated: () => audioIteratorsCreated,
+ setMuted: (newMuted: boolean) => {
+ muted = newMuted;
+ gainNode.gain.value = muted ? 0 : currentVolume;
+ },
+ setVolume: (volume: number) => {
+ currentVolume = Math.max(0, volume);
+ gainNode.gain.value = muted ? 0 : currentVolume;
+ },
+ scheduleAudioChunk,
};
};
diff --git a/packages/media/src/debug-overlay/preview-overlay.ts b/packages/media/src/debug-overlay/preview-overlay.ts
index 9f44cb686f..f665a6e870 100644
--- a/packages/media/src/debug-overlay/preview-overlay.ts
+++ b/packages/media/src/debug-overlay/preview-overlay.ts
@@ -32,16 +32,16 @@ export const drawPreviewOverlay = ({
const queuedPeriod = audioIteratorManager
.getAudioBufferIterator()
?.getQueuedPeriod();
+
+ const numberOfChunksAfterResuming =
+ audioIteratorManager?.getNumberOfChunksAfterResuming();
if (queuedPeriod) {
lines.push(
`Audio queued until: ${(queuedPeriod.until - (audioTime - audioSyncAnchor)).toFixed(3)}s`,
);
- } else if (
- audioIteratorManager?.getAudioChunksForAfterResuming()?.length &&
- audioIteratorManager?.getAudioChunksForAfterResuming()?.length > 0
- ) {
+ } else if (numberOfChunksAfterResuming) {
lines.push(
- `Audio chunks for after resuming: ${audioIteratorManager?.getAudioChunksForAfterResuming()?.length}`,
+ `Audio chunks for after resuming: ${numberOfChunksAfterResuming}`,
);
}
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index e38c997d08..af5d67aa7e 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -1,4 +1,3 @@
-import type {WrappedAudioBuffer} from 'mediabunny';
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
import type {LogLevel, useBufferState} from 'remotion';
import {Internals} from 'remotion';
@@ -6,7 +5,6 @@ import {
audioIteratorManager,
type AudioIteratorManager,
} from './audio-iterator-manager';
-import {isAlreadyQueued} from './audio/audio-preview-iterator';
import {drawPreviewOverlay} from './debug-overlay/preview-overlay';
import {getTimeInSeconds} from './get-time-in-seconds';
import {isNetworkError} from './is-network-error';
@@ -33,9 +31,6 @@ export class MediaPlayer {
private playbackRate: number;
private audioStreamIndex: number;
- private gainNode: GainNode | null = null;
- private currentVolume: number = 1;
-
private sharedAudioContext: AudioContext;
audioIteratorManager: AudioIteratorManager | null = null;
@@ -46,7 +41,6 @@ export class MediaPlayer {
private audioSyncAnchor: number = 0;
private playing = false;
- private muted = false;
private loop = false;
private fps: number;
@@ -219,9 +213,8 @@ export class MediaPlayer {
this.audioIteratorManager = audioIteratorManager({
audioTrack,
bufferState: this.bufferState,
+ sharedAudioContext: this.sharedAudioContext,
});
- this.gainNode = this.sharedAudioContext.createGain();
- this.gainNode.connect(this.sharedAudioContext.destination);
}
const startTime = getTimeInSeconds({
@@ -372,87 +365,16 @@ export class MediaPlayer {
);
}
- const queuedPeriod = this.audioIteratorManager
- ?.getAudioBufferIterator()
- ?.getQueuedPeriod();
-
- const currentTimeIsAlreadyQueued = isAlreadyQueued(newTime, queuedPeriod);
- const toBeScheduled: WrappedAudioBuffer[] = [];
-
- if (!currentTimeIsAlreadyQueued) {
- const audioSatisfyResult = await this.audioIteratorManager
- ?.getAudioBufferIterator()
- ?.tryToSatisfySeek(newTime);
-
- if (this.currentSeekNonce !== nonce) {
- return;
- }
-
- if (!audioSatisfyResult) {
- return;
- }
-
- if (audioSatisfyResult.type === 'not-satisfied') {
- if (this.audioIteratorManager) {
- await this.audioIteratorManager.startAudioIterator(
- newTime,
- nonce,
- () => this.currentSeekNonce,
- );
- }
-
- return;
- }
-
- toBeScheduled.push(...audioSatisfyResult.buffers);
- }
-
- // TODO: What is this is beyond the end of the video
- const nextTime =
- newTime +
- // start of next frame
- (1 / this.fps) * this.playbackRate +
- // need the full duration of the next frame to be queued
- (1 / this.fps) * this.playbackRate;
- const nextIsAlreadyQueued = isAlreadyQueued(nextTime, queuedPeriod);
- if (!nextIsAlreadyQueued) {
- const audioSatisfyResult = await this.audioIteratorManager
- ?.getAudioBufferIterator()
- ?.tryToSatisfySeek(nextTime);
-
- if (this.currentSeekNonce !== nonce) {
- return;
- }
-
- if (!audioSatisfyResult) {
- return;
- }
-
- if (audioSatisfyResult.type === 'not-satisfied') {
- if (this.audioIteratorManager) {
- await this.audioIteratorManager.startAudioIterator(
- nextTime,
- nonce,
- () => this.currentSeekNonce,
- );
- }
-
- return;
- }
-
- toBeScheduled.push(...audioSatisfyResult.buffers);
- }
-
- for (const buffer of toBeScheduled) {
- if (this.playing) {
- this.scheduleAudioChunk(buffer.buffer, buffer.timestamp);
- } else if (this.audioIteratorManager) {
- this.audioIteratorManager.getAudioChunksForAfterResuming().push({
- buffer: buffer.buffer,
- timestamp: buffer.timestamp,
- });
- }
- }
+ await this.audioIteratorManager?.seek({
+ newTime,
+ nonce,
+ getSeekNonce: () => this.currentSeekNonce,
+ fps: this.fps,
+ playbackRate: this.playbackRate,
+ audioSyncAnchor: this.audioSyncAnchor,
+ trimBefore: this.trimBefore,
+ getIsPlaying: () => this.playing,
+ });
}
public async play(time: number): Promise<void> {
@@ -462,57 +384,38 @@ export class MediaPlayer {
this.playing = true;
if (this.audioIteratorManager) {
- for (const chunk of this.audioIteratorManager.getAudioChunksForAfterResuming()) {
- this.scheduleAudioChunk(chunk.buffer, chunk.timestamp);
- }
+ this.audioIteratorManager.resumeScheduledAudioChunks({
+ audioSyncAnchor: this.audioSyncAnchor,
+ fps: this.fps,
+ playbackRate: this.playbackRate,
+ trimBefore: this.trimBefore,
+ });
}
if (this.sharedAudioContext.state === 'suspended') {
await this.sharedAudioContext.resume();
}
- if (this.audioIteratorManager) {
- this.audioIteratorManager.getAudioChunksForAfterResuming().length = 0;
- }
-
this.drawDebugOverlay();
}
public pause(): void {
this.playing = false;
- const toQueue = this.audioIteratorManager
- ?.getAudioBufferIterator()
- ?.removeAndReturnAllQueuedAudioNodes();
-
- if (toQueue && this.audioIteratorManager) {
- for (const chunk of toQueue) {
- this.audioIteratorManager.getAudioChunksForAfterResuming().push({
- buffer: chunk.buffer,
- timestamp: chunk.timestamp,
- });
- }
- }
+ this.audioIteratorManager?.pausePlayback();
this.drawDebugOverlay();
}
public setMuted(muted: boolean): void {
- this.muted = muted;
- if (this.gainNode) {
- this.gainNode.gain.value = muted ? 0 : this.currentVolume;
- }
+ this.audioIteratorManager?.setMuted(muted);
}
public setVolume(volume: number): void {
- if (!this.gainNode) {
+ if (!this.audioIteratorManager) {
return;
}
- const appliedVolume = Math.max(0, volume);
- this.currentVolume = appliedVolume;
- if (!this.muted) {
- this.gainNode.gain.value = appliedVolume;
- }
+ this.audioIteratorManager.setVolume(volume);
}
public setDebugOverlay(debugOverlay: boolean): void {
@@ -558,38 +461,6 @@ export class MediaPlayer {
this.audioSyncAnchor = this.sharedAudioContext.currentTime - time;
}
- private scheduleAudioChunk(
- buffer: AudioBuffer,
- mediaTimestamp: number,
- ): void {
- // TODO: Might already be scheduled, and then the playback rate changes
- // TODO: Playbackrate does not yet work
- const targetTime =
- (mediaTimestamp - (this.trimBefore ?? 0) / this.fps) / this.playbackRate;
- const delay =
- targetTime + this.audioSyncAnchor - this.sharedAudioContext.currentTime;
-
- const node = this.sharedAudioContext.createBufferSource();
- node.buffer = buffer;
- node.playbackRate.value = this.playbackRate;
- node.connect(this.gainNode!);
-
- if (delay >= 0) {
- node.start(targetTime + this.audioSyncAnchor);
- } else {
- node.start(this.sharedAudioContext.currentTime, -delay);
- }
-
- this.audioIteratorManager
- ?.getAudioBufferIterator()!
- .addQueuedAudioNode(node, mediaTimestamp, buffer);
- node.onended = () => {
- return this.audioIteratorManager
- ?.getAudioBufferIterator()!
- .removeQueuedAudioNode(node);
- };
- }
-
public onVideoFrame(
callback: (frame: CanvasImageSource) => void,
): () => void {