Skip to content

🎥 Make videos programmatically with React

cool

Jonny Burgeraff9af90328d
diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsx
index b051a3e086..cb76cbe8b3 100644
--- a/packages/core/src/audio/shared-audio-tags.tsx
+++ b/packages/core/src/audio/shared-audio-tags.tsx
@@ -59,6 +59,7 @@ export type ScheduleAudioNodeOptions = {
readonly mediaTimestamp: number;
readonly currentTime: number;
readonly scheduledTime: number;
+ readonly originalUnloopedMediaTimestamp: number;
readonly duration: number;
readonly offset: number;
};
@@ -210,6 +211,7 @@ export const SharedAudioContextProvider: React.FC<{
scheduledTime,
duration,
offset,
+ originalUnloopedMediaTimestamp,
}: ScheduleAudioNodeOptions): ScheduleAudioNodeResult => {
if (!audioContext) {
throw new Error('Audio context not found');
@@ -267,6 +269,9 @@ export const SharedAudioContextProvider: React.FC<{
'offset=' + offset.toFixed(4),
'latency=' + latency.toFixed(4),
'state=' + audioContext.state,
+ originalUnloopedMediaTimestamp !== mediaTime
+ ? 'original_ts=' + originalUnloopedMediaTimestamp.toFixed(4)
+ : '',
);
prev.scheduledEndTime = scheduledEndTime;
diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.ts
index 11516ede41..4145f8fe97 100644
--- a/packages/media/src/audio-iterator-manager.ts
+++ b/packages/media/src/audio-iterator-manager.ts
@@ -1,4 +1,4 @@
-import type {InputAudioTrack, WrappedAudioBuffer} from 'mediabunny';
+import {type InputAudioTrack} from 'mediabunny';
import {AudioBufferSink, InputDisposedError} from 'mediabunny';
import type {LogLevel} from 'remotion';
import {Internals, type ScheduleAudioNodeResult} from 'remotion';
@@ -14,12 +14,14 @@ import {
import {getScheduledTime} from './audio/get-scheduled-time';
import {StaleWaiterError, waitForTurn} from './audio/sort-by-priority';
import type {DelayPlaybackIfNotPremounting} from './delay-playback-if-not-premounting';
+import type {BufferWithMediaTimestamp} from './make-iterator-with-priming';
import type {Nonce} from './nonce-manager';
import type {SharedAudioContextForMediaPlayer} from './shared-audio-context-for-media-player';
type ScheduleAudioNode = (
node: AudioBufferSourceNode,
mediaTimestamp: number,
+ originalUnloopedMediaTimestamp: number,
) => ScheduleAudioNodeResult;
export const audioIteratorManager = ({
@@ -27,7 +29,8 @@ export const audioIteratorManager = ({
delayPlaybackHandleIfNotPremounting,
sharedAudioContext,
getIsLooping,
- getEndTime,
+ getSequenceEndTimestamp,
+ getMediaEndTimestamp,
getStartTime,
initialMuted,
drawDebugOverlay,
@@ -37,7 +40,8 @@ export const audioIteratorManager = ({
delayPlaybackHandleIfNotPremounting: () => DelayPlaybackIfNotPremounting;
sharedAudioContext: SharedAudioContextForMediaPlayer;
getIsLooping: () => boolean;
- getEndTime: () => number;
+ getSequenceEndTimestamp: () => number;
+ getMediaEndTimestamp: () => number;
getStartTime: () => number;
initialMuted: boolean;
drawDebugOverlay: () => void;
@@ -93,6 +97,7 @@ export const audioIteratorManager = ({
const scheduleAudioChunk = ({
buffer,
mediaTimestamp,
+ originalUnloopedMediaTimestamp,
playbackRate,
scheduleAudioNode,
logLevel,
@@ -102,6 +107,7 @@ export const audioIteratorManager = ({
playbackRate: number;
scheduleAudioNode: ScheduleAudioNode;
logLevel: LogLevel;
+ originalUnloopedMediaTimestamp: number;
}) => {
if (!audioBufferIterator) {
throw new Error('Audio buffer iterator not found');
@@ -116,7 +122,11 @@ export const audioIteratorManager = ({
node.playbackRate.value = playbackRate;
node.connect(gainNode);
- const started = scheduleAudioNode(node, mediaTimestamp);
+ const started = scheduleAudioNode(
+ node,
+ mediaTimestamp,
+ originalUnloopedMediaTimestamp,
+ );
if (started.type === 'not-started') {
Internals.Log.verbose(
@@ -148,7 +158,7 @@ export const audioIteratorManager = ({
scheduleAudioNode,
logLevel,
}: {
- buffer: WrappedAudioBuffer;
+ buffer: BufferWithMediaTimestamp;
playbackRate: number;
scheduleAudioNode: ScheduleAudioNode;
logLevel: LogLevel;
@@ -158,27 +168,31 @@ export const audioIteratorManager = ({
}
const startTime = getStartTime();
- const endTime = getEndTime();
+ const sequenceEndTime = getSequenceEndTimestamp();
// Skip chunks entirely outside the range
- if (buffer.timestamp + buffer.duration <= startTime) {
+ if (buffer.timestamp + buffer.buffer.duration <= startTime) {
return;
}
- if (buffer.timestamp >= endTime) {
+ if (buffer.timestamp >= sequenceEndTime) {
return;
}
const scheduledStart = Math.max(buffer.timestamp, startTime);
- const scheduledEnd = Math.min(buffer.timestamp + buffer.duration, endTime);
+ const scheduledEnd = Math.min(
+ buffer.timestamp + buffer.buffer.duration,
+ sequenceEndTime,
+ );
totalAudioScheduledInSeconds += Math.max(0, scheduledEnd - scheduledStart);
scheduleAudioChunk({
- buffer: buffer.buffer,
+ buffer: buffer.buffer.buffer,
mediaTimestamp: buffer.timestamp,
playbackRate,
scheduleAudioNode,
logLevel,
+ originalUnloopedMediaTimestamp: buffer.buffer.timestamp,
});
drawDebugOverlay();
@@ -318,7 +332,7 @@ export const audioIteratorManager = ({
const iterator = makeAudioIterator({
startFromSecond,
- maximumTimestamp: getEndTime(),
+ maximumTimestamp: getMediaEndTimestamp(),
audioSink,
logLevel,
loop,
diff --git a/packages/media/src/audio/audio-preview-iterator.ts b/packages/media/src/audio/audio-preview-iterator.ts
index 3cdccc9b35..b0a7937fbd 100644
--- a/packages/media/src/audio/audio-preview-iterator.ts
+++ b/packages/media/src/audio/audio-preview-iterator.ts
@@ -59,7 +59,7 @@ export const makeAudioIterator = ({
if (next.value) {
mostRecentTimestamp = Math.max(
mostRecentTimestamp,
- next.value.timestamp + next.value.duration,
+ next.value.timestamp + next.value.buffer.duration,
);
}
diff --git a/packages/media/src/make-iterator-with-priming.ts b/packages/media/src/make-iterator-with-priming.ts
index c90253b7ef..1f022d6fc2 100644
--- a/packages/media/src/make-iterator-with-priming.ts
+++ b/packages/media/src/make-iterator-with-priming.ts
@@ -2,21 +2,28 @@ import type {AudioBufferSink, WrappedAudioBuffer} from 'mediabunny';
const AUDIO_PRIMING_SECONDS = 0.5;
+export type BufferWithMediaTimestamp = {
+ buffer: WrappedAudioBuffer;
+ timestamp: number;
+};
+
async function* makeIteratorWithPrimingInner(
audioSink: AudioBufferSink,
timeToSeek: number,
maximumTimestamp: number,
-): AsyncGenerator<WrappedAudioBuffer, void, unknown> {
+): AsyncGenerator<BufferWithMediaTimestamp, void, unknown> {
const primingStart = Math.max(0, timeToSeek - AUDIO_PRIMING_SECONDS);
const iterator = audioSink.buffers(primingStart, maximumTimestamp);
- console.log({timeToSeek, maximumTimestamp});
for await (const buffer of iterator) {
if (buffer.timestamp + buffer.duration <= timeToSeek) {
continue;
}
- yield buffer;
+ yield {
+ buffer,
+ timestamp: buffer.timestamp,
+ };
}
}
@@ -24,13 +31,23 @@ async function* makeLoopingIterator(
audioSink: AudioBufferSink,
timeToSeek: number,
maximumTimestamp: number,
-): AsyncGenerator<WrappedAudioBuffer, void, unknown> {
+): AsyncGenerator<BufferWithMediaTimestamp, void, unknown> {
+ const duration = maximumTimestamp - timeToSeek;
+ let iteration = 0;
+
while (true) {
- yield* makeIteratorWithPrimingInner(
+ for await (const item of makeIteratorWithPrimingInner(
audioSink,
timeToSeek,
maximumTimestamp,
- );
+ )) {
+ yield {
+ buffer: item.buffer,
+ timestamp: item.timestamp + iteration * duration,
+ };
+ }
+
+ iteration++;
}
}
@@ -44,7 +61,7 @@ export const makeIteratorWithPriming = ({
timeToSeek: number;
maximumTimestamp: number;
loop: boolean;
-}): AsyncGenerator<WrappedAudioBuffer, void, unknown> => {
+}): AsyncGenerator<BufferWithMediaTimestamp, void, unknown> => {
if (loop) {
return makeLoopingIterator(audioSink, timeToSeek, maximumTimestamp);
}
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index 87e89b2ca5..e6409665a5 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -54,7 +54,7 @@ export class MediaPlayer {
private trimBefore: number | undefined;
private trimAfter: number | undefined;
- private durationInFrames: number;
+ private initialSequenceDurationInFrames: number;
private totalDuration: number | undefined;
@@ -131,7 +131,7 @@ export class MediaPlayer {
this.bufferState = bufferState;
this.isPremounting = isPremounting;
this.isPostmounting = isPostmounting;
- this.durationInFrames = durationInFrames;
+ this.initialSequenceDurationInFrames = durationInFrames;
this.nonceManager = makeNonceManager();
this.onVideoFrameCallback = onVideoFrameCallback;
this.playing = playing;
@@ -184,7 +184,16 @@ export class MediaPlayer {
return (this.trimBefore ?? 0) / this.fps;
}
- private getEndTime(): number {
+ private getSequenceEndTimestamp(): number {
+ // Cap at the media time corresponding to the end of the sequence
+ const sequenceEndMediaTime =
+ (this.initialSequenceDurationInFrames / this.fps) * this.playbackRate +
+ (this.trimBefore ?? 0) / this.fps;
+
+ return sequenceEndMediaTime;
+ }
+
+ private getMediaEndTimestamp(): number {
const mediaEndTime = calculateEndTime({
mediaDurationInSeconds: this.totalDuration!,
ifNoMediaDuration: 'fail',
@@ -193,17 +202,18 @@ export class MediaPlayer {
trimBefore: this.trimBefore,
fps: this.fps,
});
+ return mediaEndTime;
+ }
+ private getVideoEndTime(): number {
if (this.loop) {
- return mediaEndTime;
+ return this.getMediaEndTimestamp();
}
- // Cap at the media time corresponding to the end of the sequence
- const sequenceEndMediaTime =
- (this.durationInFrames / this.fps) * this.playbackRate +
- (this.trimBefore ?? 0) / this.fps;
-
- return Math.min(mediaEndTime, sequenceEndMediaTime);
+ return Math.min(
+ this.getMediaEndTimestamp(),
+ this.getSequenceEndTimestamp(),
+ );
}
private async _initialize(
@@ -275,7 +285,7 @@ export class MediaPlayer {
getOnVideoFrameCallback: () => this.onVideoFrameCallback,
logLevel: this.logLevel,
drawDebugOverlay: this.drawDebugOverlay,
- getEndTime: () => this.getEndTime(),
+ getEndTime: () => this.getVideoEndTime(),
getStartTime: () => this.getStartTime(),
getIsLooping: () => this.loop,
});
@@ -303,7 +313,8 @@ export class MediaPlayer {
this.delayPlaybackHandleIfNotPremounting,
sharedAudioContext: this.sharedAudioContext,
getIsLooping: () => this.loop,
- getEndTime: () => this.getEndTime(),
+ getMediaEndTimestamp: () => this.getMediaEndTimestamp(),
+ getSequenceEndTimestamp: () => this.getSequenceEndTimestamp(),
getStartTime: () => this.getStartTime(),
initialMuted,
drawDebugOverlay: this.drawDebugOverlay,
@@ -567,8 +578,8 @@ export class MediaPlayer {
this.sequenceOffset = offset;
}
- public setDurationInFrames(durationInFrames: number): void {
- this.durationInFrames = durationInFrames;
+ public setSequenceDurationInFrames(sequenceDurationInFrames: number): void {
+ this.initialSequenceDurationInFrames = sequenceDurationInFrames;
}
public async dispose(): Promise<void> {
@@ -619,6 +630,7 @@ export class MediaPlayer {
private scheduleAudioNode = (
node: AudioBufferSourceNode,
mediaTimestamp: number,
+ originalUnloopedMediaTimestamp: number,
): ScheduleAudioNodeResult => {
if (!this.sharedAudioContext) {
throw new Error('Shared audio context not found');
@@ -640,7 +652,7 @@ export class MediaPlayer {
}
const sequenceStartTime = this.getStartTime();
- const sequenceEndTime = this.getEndTime();
+ const sequenceEndTime = this.getSequenceEndTimestamp();
const offset = getOffset({
mediaTimestamp,
@@ -665,6 +677,7 @@ export class MediaPlayer {
offset,
}),
offset,
+ originalUnloopedMediaTimestamp,
});
};
@@ -696,6 +709,5 @@ export class MediaPlayer {
}
this.audioIteratorManager.destroyIterator();
- console.log('destroyed');
};
}
diff --git a/packages/media/src/test/audio-iterator.test.ts b/packages/media/src/test/audio-iterator.test.ts
index 048550315a..26a7168b15 100644
--- a/packages/media/src/test/audio-iterator.test.ts
+++ b/packages/media/src/test/audio-iterator.test.ts
@@ -36,7 +36,8 @@ const prepare = async (options?: {fps?: number; playbackRate?: number}) => {
scheduleAudioNode: scheduleSharedAudioNode,
},
getIsLooping: () => false,
- getEndTime: () => Infinity,
+ getMediaEndTimestamp: () => Infinity,
+ getSequenceEndTimestamp: () => Infinity,
getStartTime: () => 0,
initialMuted: false,
drawDebugOverlay: () => {},
@@ -255,7 +256,8 @@ test('should not decode + schedule audio chunks beyond the end time', async () =
}),
},
getIsLooping: () => false,
- getEndTime: () => endTime,
+ getMediaEndTimestamp: () => endTime,
+ getSequenceEndTimestamp: () => endTime,
getStartTime: () => 0,
initialMuted: false,
drawDebugOverlay: () => {},
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.ts
index fbf24c12c6..892d0de5f3 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
@@ -98,7 +98,8 @@ test('same goes for audio', async () => {
}),
},
getIsLooping: () => false,
- getEndTime: () => Infinity,
+ getMediaEndTimestamp: () => Infinity,
+ getSequenceEndTimestamp: () => Infinity,
getStartTime: () => 0,
initialMuted: false,
drawDebugOverlay: () => {},
diff --git a/packages/media/src/use-common-effects.ts b/packages/media/src/use-common-effects.ts
index 6d6bd3abe7..5a1fa3c078 100644
--- a/packages/media/src/use-common-effects.ts
+++ b/packages/media/src/use-common-effects.ts
@@ -155,7 +155,7 @@ export const useCommonEffects = ({
return;
}
- mediaPlayer.setDurationInFrames(durationInFrames);
+ mediaPlayer.setSequenceDurationInFrames(durationInFrames);
}, [durationInFrames, mediaPlayerReady, mediaPlayerRef]);
useLayoutEffect(() => {
diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsx
index 74baaf8d79..2553d915a4 100644
--- a/packages/media/src/video/video-for-preview.tsx
+++ b/packages/media/src/video/video-for-preview.tsx
@@ -204,7 +204,7 @@ const VideoForPreviewAssertedShowing: React.FC<
const initialGlobalPlaybackRate = useRef(globalPlaybackRate);
const initialPlaybackRate = useRef(playbackRate);
const initialMuted = useRef(effectiveMuted);
- const initialDurationInFrames = useRef(videoConfig.durationInFrames);
+ const initialSequenceDuration = useRef(videoConfig.durationInFrames);
const initialSequenceOffset = useRef(sequenceOffset);
const hasDrawnRealFrameRef = useRef(false);
const isPremountingRef = useRef(isPremounting);
@@ -286,7 +286,7 @@ const VideoForPreviewAssertedShowing: React.FC<
isPremounting: initialIsPremounting.current,
isPostmounting: initialIsPostmounting.current,
globalPlaybackRate: initialGlobalPlaybackRate.current,
- durationInFrames: initialDurationInFrames.current,
+ durationInFrames: initialSequenceDuration.current,
onVideoFrameCallback: initialOnVideoFrameRef.current ?? null,
playing: initialPlaying.current,
sequenceOffset: initialSequenceOffset.current,