🎥 Make videos programmatically with React
start new audio scheduling solution
Jonny Burger7303350cd2c3
diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsxindex 2cfb3bac27..9ab63faea5 100644--- a/packages/core/src/audio/shared-audio-tags.tsx+++ b/packages/core/src/audio/shared-audio-tags.tsx@@ -44,10 +44,8 @@ const EMPTY_AUDIO =export type ScheduleAudioNodeOptions = {node: AudioBufferSourceNode;+ targetTime: number;mediaTimestamp: number;- delay: number;- nodeTrimBefore: number;- nodeDuration: number | null;};type SharedContext = {@@ -156,53 +154,9 @@ export const SharedAudioContextProvider: React.FC<{return null;}- let lastScheduledEnd: number | null = null;- let lastMediaEnd: number | null = null;-- return ({- node,- mediaTimestamp,- delay,- nodeTrimBefore: trimBefore,- nodeDuration: duration,- }: ScheduleAudioNodeOptions): boolean => {- if (duration !== null && duration <= 0) {- return false;- }-- const startAt =- delay >= 0- ? audioContext.currentTime + delay- : audioContext.currentTime;- const effectiveDuration =- duration ?? (node.buffer?.duration ?? 0) - trimBefore;- node.start(startAt, trimBefore, duration ?? undefined);-- const end = startAt + effectiveDuration;- const mediaEnd = mediaTimestamp + effectiveDuration;-- const startGap =- lastScheduledEnd !== null &&- Math.abs(startAt - lastScheduledEnd) > 0.001;- const mediaGap =- lastMediaEnd !== null &&- Math.abs(mediaTimestamp - lastMediaEnd) > 0.001;-- const red = 'color: red; font-weight: bold';- const normal = '';-- // eslint-disable-next-line no-console- console.log(- `[audio-schedule] start=%c${startAt.toFixed(4)}%c dur=${effectiveDuration.toFixed(4)} end=${end.toFixed(4)} mediaStart=%c${mediaTimestamp.toFixed(4)}%c mediaEnd=${mediaEnd.toFixed(4)}`,- startGap ? red : normal,- normal,- mediaGap ? red : normal,- normal,- );-- lastScheduledEnd = end;- lastMediaEnd = mediaEnd;-+ return ({node, mediaTimestamp, targetTime}: ScheduleAudioNodeOptions) => {+ console.log('scheduleAudioNode', mediaTimestamp, targetTime);+ node.start(targetTime);return true;};}, [audioContext]);diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.tsindex 1f840d7ec9..de0bbb4235 100644--- a/packages/media/src/audio-iterator-manager.ts+++ b/packages/media/src/audio-iterator-manager.ts@@ -11,6 +11,11 @@ import {makePrewarmedAudioIteratorCache} from './prewarm-iterator-for-looping';const MAX_BUFFER_AHEAD_SECONDS = 8;+type ScheduleAudioNode = (+ node: AudioBufferSourceNode,+ mediaTimestamp: number,+) => boolean;+export const audioIteratorManager = ({audioTrack,delayPlaybackHandleIfNotPremounting,@@ -48,20 +53,11 @@ export const audioIteratorManager = ({mediaTimestamp,playbackRate,scheduleAudioNode,- maxDuration,- bufferOffset,}: {buffer: AudioBuffer;mediaTimestamp: number;playbackRate: number;- scheduleAudioNode: (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => boolean;- maxDuration: number | null;- bufferOffset: number;+ scheduleAudioNode: ScheduleAudioNode;}) => {if (!audioBufferIterator) {throw new Error('Audio buffer iterator not found');@@ -76,12 +72,7 @@ export const audioIteratorManager = ({node.playbackRate.value = playbackRate;node.connect(gainNode);- const started = scheduleAudioNode(- node,- mediaTimestamp,- maxDuration,- bufferOffset,- );+ const started = scheduleAudioNode(node, mediaTimestamp);if (!started) {node.disconnect();@@ -90,13 +81,7 @@ export const audioIteratorManager = ({const iterator = audioBufferIterator;- iterator.addQueuedAudioNode(- node,- mediaTimestamp,- buffer,- maxDuration,- bufferOffset,- );+ iterator.addQueuedAudioNode(node, mediaTimestamp, buffer);node.onended = () => {// Some leniancy is needed as we find that sometimes onended is fired a bit too earlysetTimeout(() => {@@ -114,12 +99,7 @@ export const audioIteratorManager = ({getIsPlaying: () => boolean;buffer: WrappedAudioBuffer;playbackRate: number;- scheduleAudioNode: (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => boolean;+ scheduleAudioNode: ScheduleAudioNode;}) => {if (muted) {return;@@ -137,24 +117,12 @@ export const audioIteratorManager = ({return;}- // Leading trim- const bufferOffset = Math.max(0, startTime - buffer.timestamp);- const adjustedTimestamp = buffer.timestamp + bufferOffset;-- // Trailing trim (from the adjusted start)- const maxDuration =- adjustedTimestamp + (buffer.duration - bufferOffset) > endTime- ? endTime - adjustedTimestamp- : null;-if (getIsPlaying()) {scheduleAudioChunk({buffer: buffer.buffer,- mediaTimestamp: adjustedTimestamp,+ mediaTimestamp: buffer.timestamp,playbackRate,scheduleAudioNode,- maxDuration,- bufferOffset,});} else {if (!audioBufferIterator) {@@ -163,9 +131,7 @@ export const audioIteratorManager = ({audioBufferIterator.addChunkForAfterResuming(buffer.buffer,- adjustedTimestamp,- maxDuration,- bufferOffset,+ buffer.timestamp,);}@@ -183,12 +149,7 @@ export const audioIteratorManager = ({nonce: Nonce;playbackRate: number;getIsPlaying: () => boolean;- scheduleAudioNode: (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => boolean;+ scheduleAudioNode: ScheduleAudioNode;}) => {if (muted) {return;@@ -274,12 +235,7 @@ export const audioIteratorManager = ({nonce: Nonce;playbackRate: number;getIsPlaying: () => boolean;- scheduleAudioNode: (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => boolean;+ scheduleAudioNode: ScheduleAudioNode;}) => {if (muted) {return;@@ -367,12 +323,7 @@ export const audioIteratorManager = ({scheduleAudioNode,}: {playbackRate: number;- scheduleAudioNode: (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => boolean;+ scheduleAudioNode: ScheduleAudioNode;}) => {if (muted) {return;@@ -388,8 +339,6 @@ export const audioIteratorManager = ({mediaTimestamp: chunk.timestamp,playbackRate,scheduleAudioNode,- maxDuration: chunk.maxDuration,- bufferOffset: chunk.bufferOffset,});}};diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsxindex 227028a18f..e45339325f 100644--- a/packages/media/src/audio/audio-for-preview.tsx+++ b/packages/media/src/audio/audio-for-preview.tsx@@ -373,7 +373,7 @@ const AudioForPreviewAssertedShowing: React.FC<if (!audioPlayer) return;if (playing && !isPlayerBuffering) {- audioPlayer.play(currentTimeRef.current);+ audioPlayer.play();} else {audioPlayer.pause();}diff --git a/packages/media/src/audio/audio-preview-iterator.ts b/packages/media/src/audio/audio-preview-iterator.tsindex ac33e4fced..966ac3d4b6 100644--- a/packages/media/src/audio/audio-preview-iterator.ts+++ b/packages/media/src/audio/audio-preview-iterator.ts@@ -8,8 +8,6 @@ export type QueuedNode = {node: AudioBufferSourceNode;timestamp: number;buffer: AudioBuffer;- maxDuration: number | null;- bufferOffset: number;};export const makeAudioIterator = (@@ -22,8 +20,6 @@ export const makeAudioIterator = (const audioChunksForAfterResuming: {buffer: AudioBuffer;timestamp: number;- maxDuration: number | null;- bufferOffset: number;}[] = [];let mostRecentTimestamp = -Infinity;let pendingNext: Promise<IteratorResult<WrappedAudioBuffer, void>> | null =@@ -194,29 +190,17 @@ export const makeAudioIterator = (return nodes;};- const addChunkForAfterResuming = (- buffer: AudioBuffer,- timestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => {+ const addChunkForAfterResuming = (buffer: AudioBuffer, timestamp: number) => {audioChunksForAfterResuming.push({buffer,timestamp,- maxDuration,- bufferOffset,});};const moveQueuedChunksToPauseQueue = () => {const toQueue = removeAndReturnAllQueuedAudioNodes();for (const chunk of toQueue) {- addChunkForAfterResuming(- chunk.buffer,- chunk.timestamp,- chunk.maxDuration,- chunk.bufferOffset,- );+ addChunkForAfterResuming(chunk.buffer, chunk.timestamp);}};@@ -249,15 +233,11 @@ export const makeAudioIterator = (node: AudioBufferSourceNode,timestamp: number,buffer: AudioBuffer,- maxDuration: number | null,- bufferOffset: number,) => {queuedAudioNodes.push({node,timestamp,buffer,- maxDuration,- bufferOffset,});},removeQueuedAudioNode: (node: AudioBufferSourceNode) => {diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 81fea19261..879d04e27c 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -374,7 +374,10 @@ export class MediaPlayer {}const shouldSeekAudio =- this.audioIteratorManager && this.getAudioPlaybackTime() !== newTime;+ this.audioIteratorManager &&+ this.getAudioPlaybackTime(+ this.sharedAudioContext?.audioContext.currentTime ?? 0,+ ) !== newTime;try {await Promise.all([@@ -401,12 +404,7 @@ export class MediaPlayer {}}- public async playAudio(time: number): Promise<void> {- const newTime = this.getTrimmedTime(time);- if (newTime === null) {- throw new Error(`should have asserted that the time is not null`);- }-+ public async playAudio(): Promise<void> {if (this.audioIteratorManager) {this.audioIteratorManager.resumeScheduledAudioChunks({playbackRate: this.playbackRate * this.globalPlaybackRate,@@ -418,18 +416,19 @@ export class MediaPlayer {this.sharedAudioContext &&this.sharedAudioContext.audioContext.state === 'suspended') {+ console.log('resume');await this.sharedAudioContext.audioContext.resume();}}- public async play(time: number): Promise<void> {+ public async play(): Promise<void> {if (this.playing) {return;}this.playing = true;- await this.playAudio(time);+ await this.playAudio();this.drawDebugOverlay();}@@ -619,38 +618,38 @@ export class MediaPlayer {private scheduleAudioNode = (node: AudioBufferSourceNode,mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,): boolean => {if (!this.sharedAudioContext) {throw new Error('Shared audio context not found');}- const currentTime = this.getAudioPlaybackTime();- const combinedPlaybackRate = this.playbackRate * this.globalPlaybackRate;- const delayWithoutPlaybackRate = mediaTimestamp - currentTime;- const delay = delayWithoutPlaybackRate / combinedPlaybackRate;- const mediaOffset = Math.max(0, -delayWithoutPlaybackRate);- const trimBefore = bufferOffset + mediaOffset;- const nodeDuration =- maxDuration !== null ? maxDuration - mediaOffset : null;+ const {audioContext} = this.sharedAudioContext;+ const {currentTime} = audioContext;++ const globalTime =+ (currentTime - this.sharedAudioContext.audioSyncAnchor.value) *+ this.globalPlaybackRate;+ const localTime = this.getTrimmedTime(globalTime - this.sequenceOffset);+ if (localTime === null) {+ throw new Error('hmm, should not render!');+ }++ const targetTime = (mediaTimestamp - localTime) / this.playbackRate;+return this.sharedAudioContext.scheduleAudioNode({node,mediaTimestamp,- delay,- nodeTrimBefore: trimBefore,- nodeDuration,+ targetTime: targetTime + currentTime,});};- private getAudioPlaybackTime(): number {+ private getAudioPlaybackTime(currentTime: number): number {if (!this.sharedAudioContext) {throw new Error('Shared audio context not found');}const globalTime =- (this.sharedAudioContext.audioContext.currentTime -- this.sharedAudioContext.audioSyncAnchor.value) *+ (currentTime - this.sharedAudioContext.audioSyncAnchor.value) *this.globalPlaybackRate;const localTime = globalTime - this.sequenceOffset;diff --git a/packages/media/src/set-global-time-anchor.ts b/packages/media/src/set-global-time-anchor.tsindex 5a1ba7d676..8724144a24 100644--- a/packages/media/src/set-global-time-anchor.ts+++ b/packages/media/src/set-global-time-anchor.ts@@ -18,5 +18,6 @@ export const setGlobalTimeAnchor = ({return;}+ console.log('set new anchor', absoluteTimeInSeconds, shift);audioSyncAnchor.value = newAnchor;};diff --git a/packages/media/src/shared-audio-context-for-media-player.ts b/packages/media/src/shared-audio-context-for-media-player.tsindex 4a7351aaa9..c290011e21 100644--- a/packages/media/src/shared-audio-context-for-media-player.ts+++ b/packages/media/src/shared-audio-context-for-media-player.ts@@ -1,9 +1,7 @@export type ScheduleAudioNodeOptions = {node: AudioBufferSourceNode;mediaTimestamp: number;- delay: number;- nodeTrimBefore: number;- nodeDuration: number | null;+ targetTime: number;};export type SharedAudioContextForMediaPlayer = {diff --git a/packages/media/src/test/audio-iterator.test.ts b/packages/media/src/test/audio-iterator.test.tsindex 6fbbd38f7e..e0258c56b2 100644--- a/packages/media/src/test/audio-iterator.test.ts+++ b/packages/media/src/test/audio-iterator.test.ts@@ -42,22 +42,7 @@ const prepare = async () => {test('media player should work', async () => {const scheduledChunks: number[] = [];- const scheduleAudioNode = (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => {- node.start(mediaTimestamp, bufferOffset, maxDuration ?? undefined);- setTimeout(- () => {- node.stop();- },- (maxDuration ?? node.buffer?.duration ?? 0) * 1000,- );- scheduledChunks.push(mediaTimestamp);- return true;- };+ const scheduleAudioNode = () => true;const {manager, playbackRate, getIsPlaying} = await prepare();@@ -98,22 +83,7 @@ test('should not create too many iterators when the audio ends', async () => {const {manager, playbackRate, getIsPlaying} = await prepare();const scheduledChunks: number[] = [];- const scheduleAudioNode = (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => {- node.start(mediaTimestamp, bufferOffset, maxDuration ?? undefined);- setTimeout(- () => {- node.stop();- },- (maxDuration ?? node.buffer?.duration ?? 0) * 1000,- );- scheduledChunks.push(mediaTimestamp);- return true;- };+ const scheduleAudioNode = () => true;await manager.seek({newTime: 9.97,@@ -147,22 +117,7 @@ test('should create more iterators when seeking ', async () => {const {manager, playbackRate, getIsPlaying} = await prepare();const scheduledChunks: number[] = [];- const scheduleAudioNode = (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => {- node.start(mediaTimestamp, bufferOffset, maxDuration ?? undefined);- setTimeout(- () => {- node.stop();- },- (maxDuration ?? node.buffer?.duration ?? 0) * 1000,- );- scheduledChunks.push(mediaTimestamp);- return true;- };+ const scheduleAudioNode = () => true;await manager.seek({newTime: 0,@@ -216,22 +171,7 @@ test('should not schedule duplicate chunks with playbackRate=0.5', async () => {});const scheduledChunks: number[] = [];- const scheduleAudioNode = (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => {- node.start(mediaTimestamp, bufferOffset, maxDuration ?? undefined);- setTimeout(- () => {- node.stop();- },- (maxDuration ?? node.buffer?.duration ?? 0) * 1000,- );- scheduledChunks.push(mediaTimestamp);- return true;- };+ const scheduleAudioNode = () => true;const fps = 25;const playbackRate = 0.5;@@ -290,26 +230,7 @@ test('should not decode + schedule audio chunks beyond the end time', async () =maxDuration: number | null;bufferDuration: number;}[] = [];- const scheduleAudioNode = (- node: AudioBufferSourceNode,- mediaTimestamp: number,- maxDuration: number | null,- bufferOffset: number,- ) => {- node.start(mediaTimestamp, bufferOffset, maxDuration ?? undefined);- setTimeout(- () => {- node.stop();- },- (maxDuration ?? node.buffer?.duration ?? 0) * 1000,- );- scheduledChunks.push({- timestamp: mediaTimestamp,- maxDuration,- bufferDuration: node.buffer?.duration ?? 0,- });- return true;- };+ const scheduleAudioNode = () => true;// Simulate playback frame by frame, seeking past the end timefor (let frame = 0; frame < 30; frame++) {diff --git a/packages/media/src/test/video-with-no-frames-in-beginning.test.ts b/packages/media/src/test/video-with-no-frames-in-beginning.test.tsindex 029c0694e4..66e4b3fefe 100644--- a/packages/media/src/test/video-with-no-frames-in-beginning.test.ts+++ b/packages/media/src/test/video-with-no-frames-in-beginning.test.ts@@ -104,10 +104,7 @@ test('same goes for audio', async () => {playbackRate: 1,startFromSecond: 0.06671494248275864,getIsPlaying: () => true,- scheduleAudioNode: (node, mediaTimestamp, maxDuration, bufferOffset) => {- node.start(mediaTimestamp, bufferOffset, maxDuration ?? undefined);- return true;- },+ scheduleAudioNode: () => true,});await manager.seek({@@ -115,10 +112,7 @@ test('same goes for audio', async () => {nonce: nonceManager.createAsyncOperation(),playbackRate: 1,getIsPlaying: () => true,- scheduleAudioNode: (node, _mediaTimestamp, maxDuration, bufferOffset) => {- node.start(1, bufferOffset, maxDuration ?? undefined);- return true;- },+ scheduleAudioNode: () => true,});const iterators = manager.getAudioIteratorsCreated();diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsxindex 975b15cd9f..09f8bd4d7c 100644--- a/packages/media/src/video/video-for-preview.tsx+++ b/packages/media/src/video/video-for-preview.tsx@@ -394,10 +394,7 @@ const VideoForPreviewAssertedShowing: React.FC<if (!mediaPlayer) return;if (isNextFrameGoingToPlay) {- const currentTimeUntilZero =- // Premounting does not consider the local playback rate, just the global one.- premountFramesRemaining / videoConfig.fps / globalPlaybackRate;- mediaPlayer.playAudio(currentTimeRef.current - currentTimeUntilZero);+ mediaPlayer.playAudio();}}, [isNextFrameGoingToPlay,@@ -412,7 +409,7 @@ const VideoForPreviewAssertedShowing: React.FC<if (playing && !isPlayerBuffering && !isNextFrameGoingToPlay) {// Play does nothing if already playing, so it can be called multiple times.- mediaPlayer.play(currentTimeRef.current);+ mediaPlayer.play();} else {// Pause will do the work all over again and check if there are scheduled nodes.// This is why isNextFrameGoingToPlay is the in the dependency array.