Skip to content

🎥 Make videos programmatically with React

new audio iterator

JonnyBurgerb77d17e130f5
diff --git a/packages/media/src/audio/audio-preview-iterator.ts b/packages/media/src/audio/audio-preview-iterator.ts
index 1059e973fa..7d2fdd007f 100644
--- a/packages/media/src/audio/audio-preview-iterator.ts
+++ b/packages/media/src/audio/audio-preview-iterator.ts
@@ -1,4 +1,5 @@
-import type {AudioBufferSink} from 'mediabunny';
+import type {AudioBufferSink, WrappedAudioBuffer} from 'mediabunny';
+import {roundTo4Digits} from '../helpers/round-to-4-digits';
export const HEALTHY_BUFFER_THRESHOLD_SECONDS = 1;
@@ -18,6 +19,141 @@ export const makeAudioIterator = (
queuedAudioNodes.clear();
};
+ let lastReturnedBuffer: WrappedAudioBuffer | null = null;
+ let iteratorEnded = false;
+
+ const getNextOrNullIfNotAvailable = async () => {
+ const next = iterator.next();
+ const result = await Promise.race([
+ next,
+ new Promise<void>((resolve) => {
+ Promise.resolve().then(() => resolve());
+ }),
+ ]);
+
+ if (!result) {
+ return {
+ type: 'need-to-wait-for-it' as const,
+ waitPromise: async () => {
+ const res = await next;
+ if (res.value) {
+ lastReturnedBuffer = res.value;
+ } else {
+ iteratorEnded = true;
+ }
+
+ return res.value;
+ },
+ };
+ }
+
+ if (result.value) {
+ lastReturnedBuffer = result.value;
+ } else {
+ iteratorEnded = true;
+ }
+
+ return {
+ type: 'got-buffer-or-end' as const,
+ buffer: result.value ?? null,
+ };
+ };
+
+ const tryToSatisfySeek = async (
+ time: number,
+ ): Promise<
+ | {
+ type: 'not-satisfied';
+ reason: string;
+ }
+ | {
+ type: 'satisfied';
+ buffer: WrappedAudioBuffer;
+ }
+ > => {
+ if (lastReturnedBuffer) {
+ const bufferTimestamp = roundTo4Digits(lastReturnedBuffer.timestamp);
+ if (roundTo4Digits(time) < bufferTimestamp) {
+ return {
+ type: 'not-satisfied' as const,
+ reason: `iterator is too far, most recently returned ${bufferTimestamp}`,
+ };
+ }
+
+ const bufferEndTimestamp = roundTo4Digits(
+ lastReturnedBuffer.timestamp + lastReturnedBuffer.duration,
+ );
+ if (roundTo4Digits(time) > bufferEndTimestamp) {
+ return {
+ type: 'not-satisfied' as const,
+ reason: `iterator is too far, most recently returned ${bufferEndTimestamp}`,
+ };
+ }
+
+ return {
+ type: 'satisfied' as const,
+ buffer: lastReturnedBuffer,
+ };
+ }
+
+ if (iteratorEnded) {
+ if (lastReturnedBuffer) {
+ return {
+ type: 'satisfied' as const,
+ buffer: lastReturnedBuffer,
+ };
+ }
+
+ return {
+ type: 'not-satisfied' as const,
+ reason: 'iterator ended',
+ };
+ }
+
+ while (true) {
+ const buffer = await getNextOrNullIfNotAvailable();
+ if (buffer.type === 'need-to-wait-for-it') {
+ return {
+ type: 'not-satisfied' as const,
+ reason: 'iterator did not have buffer ready',
+ };
+ }
+
+ if (buffer.type === 'got-buffer-or-end') {
+ if (buffer.buffer === null) {
+ iteratorEnded = true;
+ if (lastReturnedBuffer) {
+ return {
+ type: 'satisfied' as const,
+ buffer: lastReturnedBuffer,
+ };
+ }
+
+ return {
+ type: 'not-satisfied' as const,
+ reason: 'iterator ended and did not have buffer ready',
+ };
+ }
+
+ const bufferTimestamp = roundTo4Digits(buffer.buffer.timestamp);
+ const bufferEndTimestamp = roundTo4Digits(
+ buffer.buffer.timestamp + buffer.buffer.duration,
+ );
+ const timestamp = roundTo4Digits(time);
+ if (bufferTimestamp <= timestamp && bufferEndTimestamp > timestamp) {
+ return {
+ type: 'satisfied' as const,
+ buffer: buffer.buffer,
+ };
+ }
+
+ continue;
+ }
+
+ throw new Error('Unreachable');
+ }
+ };
+
return {
cleanupAudioQueue,
destroy: () => {
@@ -37,6 +173,7 @@ export const makeAudioIterator = (
removeQueuedAudioNode: (node: AudioBufferSourceNode) => {
queuedAudioNodes.delete(node);
},
+ tryToSatisfySeek,
};
};
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index fa26281b70..486f03f05b 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -21,8 +21,6 @@ import {
type VideoIterator,
} from './video/video-preview-iterator';
-const AUDIO_BUFFER_TOLERANCE_THRESHOLD = 0.1;
-
export type MediaPlayerInitResult =
| {type: 'success'; durationInSeconds: number}
| {type: 'unknown-container-format'}
@@ -70,11 +68,8 @@ export class MediaPlayer {
private totalDuration: number | undefined;
// for remotion buffer state
- private isBuffering = false;
private onBufferingChangeCallback?: (isBuffering: boolean) => void;
- private mediaEnded = false;
-
private debugOverlay = false;
private onVideoFrameCallback?: (frame: CanvasImageSource) => void;
@@ -264,7 +259,7 @@ export class MediaPlayer {
this.initialized = true;
try {
- this.startAudioIterator(startTime);
+ this.startAudioIterator(startTime, this.currentSeekNonce);
await this.startVideoIterator(startTime, this.currentSeekNonce);
} catch (error) {
if (this.isDisposalError()) {
@@ -357,23 +352,33 @@ export class MediaPlayer {
return;
}
- const satisfyResult =
- await this.videoFrameIterator?.tryToSatisfySeek(newTime);
+ const [videoSatisfyResult, audioSatisfyResult] = await Promise.all([
+ this.videoFrameIterator?.tryToSatisfySeek(newTime),
+ this.audioBufferIterator?.tryToSatisfySeek(newTime),
+ ]);
- if (satisfyResult?.type === 'satisfied') {
- this.drawFrame(satisfyResult.frame);
- return;
+ const newAudioSyncAnchor = this.sharedAudioContext.currentTime - newTime;
+ const diff = Math.abs(newAudioSyncAnchor - this.audioSyncAnchor);
+ if (diff > 0.1) {
+ this.audioSyncAnchor = this.sharedAudioContext.currentTime - newTime;
}
- if (this.currentSeekNonce !== nonce) {
- return;
+ if (videoSatisfyResult?.type === 'satisfied') {
+ this.drawFrame(videoSatisfyResult.frame);
+ } else if (this.currentSeekNonce === nonce) {
+ this.startVideoIterator(newTime, nonce);
}
- this.mediaEnded = false;
- this.audioSyncAnchor = this.sharedAudioContext.currentTime - newTime;
+ if (audioSatisfyResult?.type === 'satisfied') {
+ this.scheduleAudioChunk(
+ audioSatisfyResult.buffer.buffer,
+ audioSatisfyResult.buffer.timestamp,
+ );
+ } else if (this.currentSeekNonce === nonce) {
+ this.startAudioIterator(newTime, nonce);
+ }
- this.startAudioIterator(newTime);
- this.startVideoIterator(newTime, nonce);
+ this.startAudioIterator(newTime, nonce);
}
public async play(): Promise<void> {
@@ -523,26 +528,39 @@ export class MediaPlayer {
);
};
- private startAudioIterator = (startFromSecond: number): void => {
+ private startAudioIterator = async (
+ startFromSecond: number,
+ nonce: number,
+ ): Promise<void> => {
if (!this.hasAudio()) return;
- // Clean up existing audio iterator
this.audioBufferIterator?.destroy();
+ const iterator = makeAudioIterator(this.audioSink!, startFromSecond);
+ this.audioBufferIterator = iterator;
- try {
- const iterator = makeAudioIterator(this.audioSink!, startFromSecond);
- this.audioBufferIterator = iterator;
- this.runAudioIterator(startFromSecond, iterator);
- } catch (error) {
- if (this.isDisposalError()) {
- return;
- }
+ const result = await iterator.getNext();
- Internals.Log.error(
- {logLevel: this.logLevel, tag: '@remotion/media'},
- '[MediaPlayer] Failed to start audio iterator',
- error,
- );
+ if (iterator.isDestroyed()) {
+ return;
+ }
+
+ if (nonce !== this.currentSeekNonce) {
+ return;
+ }
+
+ if (this.audioBufferIterator.isDestroyed()) {
+ return;
+ }
+
+ if (!result.value) {
+ // media ended
+ return;
+ }
+
+ const {buffer, timestamp} = result.value;
+
+ if (this.playing) {
+ this.scheduleAudioChunk(buffer, timestamp);
}
};
@@ -587,89 +605,11 @@ export class MediaPlayer {
return;
}
- if (frameResult.value) {
- this.audioSyncAnchor =
- this.sharedAudioContext.currentTime - frameResult.value.timestamp;
-
- this.drawFrame(frameResult.value);
- } else {
+ if (!frameResult.value) {
// media ended
+ return;
}
- };
-
- private runAudioIterator = async (
- startFromSecond: number,
- audioIterator: AudioIterator,
- ): Promise<void> => {
- if (!this.hasAudio()) return;
-
- try {
- let isFirstBuffer = true;
-
- while (true) {
- if (audioIterator.isDestroyed()) {
- return;
- }
-
- const result = await audioIterator.getNext();
-
- // media has ended
- if (result.done || !result.value) {
- this.mediaEnded = true;
- break;
- }
-
- const {buffer, timestamp} = result.value;
- if (this.playing) {
- if (isFirstBuffer) {
- this.audioSyncAnchor =
- this.sharedAudioContext.currentTime - timestamp;
- isFirstBuffer = false;
- }
-
- // if timestamp is less than timeToSeek, skip
- // context: for some reason, mediabunny returns buffer at 9.984s, when requested at 10s
- if (timestamp < startFromSecond - AUDIO_BUFFER_TOLERANCE_THRESHOLD) {
- continue;
- }
-
- this.scheduleAudioChunk(buffer, timestamp);
- }
-
- const playbackTime = this.getPlaybackTime();
- if (playbackTime === null) {
- continue;
- }
-
- if (timestamp - playbackTime >= 1) {
- await new Promise<void>((resolve) => {
- const check = () => {
- const currentPlaybackTime = this.getPlaybackTime();
- if (
- currentPlaybackTime !== null &&
- timestamp - currentPlaybackTime < 1
- ) {
- resolve();
- } else {
- requestAnimationFrame(check);
- }
- };
-
- check();
- });
- }
- }
- } catch (error) {
- if (this.isDisposalError()) {
- return;
- }
-
- Internals.Log.error(
- {logLevel: this.logLevel, tag: '@remotion/media'},
- '[MediaPlayer] Failed to run audio iterator',
- error,
- );
- }
+ this.drawFrame(frameResult.value);
};
}