Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Fix looped audio dropping out after multiple loop iterations (#8978)

iliya-vidrush2fa2c1b09f0f
diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsx
index f5221fd699..01a5478d25 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 ScheduleAudioNodeResult =
export type ScheduleAudioNodeOptions = {
readonly node: AudioBufferSourceNode;
readonly mediaTimestamp: number;
+ readonly sourceOffset: number;
readonly scheduledTime: number;
readonly originalUnloopedMediaTimestamp: number;
readonly duration: number;
@@ -253,6 +254,7 @@ export const SharedAudioContextProvider: React.FC<{
return ({
node,
mediaTimestamp,
+ sourceOffset,
scheduledTime,
duration,
offset,
@@ -288,7 +290,7 @@ export const SharedAudioContextProvider: React.FC<{
const scheduledEndTime =
scheduledTime + duration / node.playbackRate.value;
- const mediaTime = mediaTimestamp + offset;
+ const mediaTime = mediaTimestamp + offset - sourceOffset;
const mediaEndTime = mediaTime + duration;
diff --git a/packages/media/src/audio-iterator-manager.ts b/packages/media/src/audio-iterator-manager.ts
index cd06c12505..b33836b33f 100644
--- a/packages/media/src/audio-iterator-manager.ts
+++ b/packages/media/src/audio-iterator-manager.ts
@@ -19,7 +19,11 @@ import {
waitForTurn,
} from './audio/sort-by-priority';
import type {DelayPlaybackIfNotPremounting} from './delay-playback-if-not-premounting';
-import type {BufferWithMediaTimestamp} from './make-iterator-with-priming';
+import {
+ makeIteratorWithPriming,
+ makeLoopingIterator,
+ type AudioBufferSlice,
+} from './make-iterator-with-priming';
import type {Nonce} from './nonce-manager';
import type {SharedAudioContextForMediaPlayer} from './shared-audio-context-for-media-player';
@@ -27,8 +31,37 @@ type ScheduleAudioNode = (
node: AudioBufferSourceNode,
mediaTimestamp: number,
originalUnloopedMediaTimestamp: number,
+ sourceOffsetInSeconds: number,
+ sourceDurationInSeconds: number,
) => ScheduleAudioNodeResult;
+export type AudioIteratorAnchor = {
+ // The unlooped time in seconds at which the current iterator was started
+ unloopedStartInSeconds: number;
+ // The media timestamp emitted by the current iterator at that unlooped time
+ mediaStartInSeconds: number;
+};
+
+// Convert an unlooped composition time into the iterator's continuous media
+// timeline using the anchor established when the iterator was started. The
+// looping iterator emits timestamps that continue monotonically across loop
+// iterations, so both the scheduler (getTargetTime) and the seek dedup must
+// map times into this same frame via the identical formula.
+export const anchorToContinuousTime = ({
+ anchor,
+ unloopedTimeInSeconds,
+ playbackRate,
+}: {
+ anchor: AudioIteratorAnchor;
+ unloopedTimeInSeconds: number;
+ playbackRate: number;
+}): number => {
+ return (
+ anchor.mediaStartInSeconds +
+ (unloopedTimeInSeconds - anchor.unloopedStartInSeconds) * playbackRate
+ );
+};
+
export const audioIteratorManager = ({
audioTrack,
delayPlaybackHandleIfNotPremounting,
@@ -83,6 +116,10 @@ export const audioIteratorManager = ({
const audioSink = new AudioBufferSink(audioTrack);
let audioBufferIterator: AudioIterator | null = null;
+ // When looping, the iterator emits timestamps that continue monotonically
+ // across loop iterations instead of wrapping. This anchor maps the unlooped
+ // time to that continuous timeline so the scheduler can align chunks.
+ let currentAnchor: AudioIteratorAnchor | null = null;
let audioIteratorsCreated = 0;
let totalAudioScheduledInSeconds = 0;
let currentDelayHandle: {unblock: () => void} | null = null;
@@ -124,6 +161,8 @@ export const audioIteratorManager = ({
buffer,
mediaTimestamp,
originalUnloopedMediaTimestamp,
+ sourceOffsetInSeconds,
+ sourceDurationInSeconds,
playbackRate,
scheduleAudioNode,
logLevel,
@@ -134,6 +173,8 @@ export const audioIteratorManager = ({
scheduleAudioNode: ScheduleAudioNode;
logLevel: LogLevel;
originalUnloopedMediaTimestamp: number;
+ sourceOffsetInSeconds: number;
+ sourceDurationInSeconds: number;
}) => {
if (!audioBufferIterator) {
throw new Error('Audio buffer iterator not found');
@@ -152,6 +193,8 @@ export const audioIteratorManager = ({
node,
mediaTimestamp,
originalUnloopedMediaTimestamp,
+ sourceOffsetInSeconds,
+ sourceDurationInSeconds,
);
if (started.type === 'not-started') {
@@ -170,7 +213,9 @@ export const audioIteratorManager = ({
node,
timestamp: mediaTimestamp,
buffer,
+ sourceDurationInSeconds,
scheduledTime: started.scheduledTime,
+ playbackRate,
scheduledAtAnchor: sharedAudioContext.audioSyncAnchor.value,
});
};
@@ -181,7 +226,7 @@ export const audioIteratorManager = ({
scheduleAudioNode,
logLevel,
}: {
- buffer: BufferWithMediaTimestamp;
+ buffer: AudioBufferSlice;
playbackRate: number;
scheduleAudioNode: ScheduleAudioNode;
logLevel: LogLevel;
@@ -194,28 +239,33 @@ export const audioIteratorManager = ({
const sequenceEndTime = getSequenceEndTimestamp();
// Skip chunks entirely outside the range
- if (buffer.timestamp + buffer.buffer.duration <= startTime) {
+ if (
+ buffer.timelineTimestamp + buffer.sourceDurationInSeconds <=
+ startTime
+ ) {
return;
}
- if (buffer.timestamp >= sequenceEndTime) {
+ if (buffer.timelineTimestamp >= sequenceEndTime) {
return;
}
- const scheduledStart = Math.max(buffer.timestamp, startTime);
+ const scheduledStart = Math.max(buffer.timelineTimestamp, startTime);
const scheduledEnd = Math.min(
- buffer.timestamp + buffer.buffer.duration,
+ buffer.timelineTimestamp + buffer.sourceDurationInSeconds,
sequenceEndTime,
);
totalAudioScheduledInSeconds += Math.max(0, scheduledEnd - scheduledStart);
scheduleAudioChunk({
buffer: buffer.buffer.buffer,
- mediaTimestamp: buffer.timestamp,
+ mediaTimestamp: buffer.timelineTimestamp,
playbackRate,
scheduleAudioNode,
logLevel,
originalUnloopedMediaTimestamp: buffer.buffer.timestamp,
+ sourceOffsetInSeconds: buffer.sourceOffsetInSeconds,
+ sourceDurationInSeconds: buffer.sourceDurationInSeconds,
});
drawDebugOverlay();
@@ -290,7 +340,7 @@ export const audioIteratorManager = ({
return;
}
- onScheduled(result.value.timestamp);
+ onScheduled(result.value.timelineTimestamp);
notifyNodeScheduled();
onAudioChunk({
@@ -337,6 +387,7 @@ export const audioIteratorManager = ({
nonce,
playbackRate,
startFromSecond,
+ unloopedStartFromSecond,
scheduleAudioNode,
getTargetTime,
logLevel,
@@ -345,6 +396,7 @@ export const audioIteratorManager = ({
getAudioContextCurrentTimeMockedInTest,
}: {
startFromSecond: number;
+ unloopedStartFromSecond: number;
nonce: Nonce;
playbackRate: number;
scheduleAudioNode: ScheduleAudioNode;
@@ -372,14 +424,29 @@ export const audioIteratorManager = ({
const delayHandle = delayPlaybackHandleIfNotPremounting();
currentDelayHandle = delayHandle;
+ currentAnchor = {
+ unloopedStartInSeconds: unloopedStartFromSecond,
+ mediaStartInSeconds: startFromSecond,
+ };
+
+ const maximumContinuousTimestamp =
+ startFromSecond + getSequenceDurationInSeconds() * playbackRate;
+ const source = loop
+ ? makeLoopingIterator({
+ audioSink,
+ seekTimeInSeconds: startFromSecond,
+ loopStartInSeconds: getStartTime(),
+ segmentEndInSeconds: maximumTimestamp,
+ maximumContinuousTimestamp,
+ })
+ : makeIteratorWithPriming({
+ audioSink,
+ timeToSeek: startFromSecond,
+ maximumTimestamp,
+ });
const iterator = makeAudioIterator({
startFromSecond,
- maximumTimestamp,
- audioSink,
- logLevel,
- loop,
- playbackRate,
- sequenceDurationInSeconds: getSequenceDurationInSeconds(),
+ iterator: source,
unscheduleAudioNode,
});
audioIteratorsCreated++;
@@ -415,8 +482,10 @@ export const audioIteratorManager = ({
const seek = ({
newTime,
+ unloopedNewTime,
nonce,
playbackRate,
+ localPlaybackRate,
scheduleAudioNode,
getTargetTime,
logLevel,
@@ -429,8 +498,10 @@ export const audioIteratorManager = ({
getAudioContextCurrentTimeMockedInTest,
}: {
newTime: number;
+ unloopedNewTime: number;
nonce: Nonce;
playbackRate: number;
+ localPlaybackRate: number;
scheduleAudioNode: ScheduleAudioNode;
getTargetTime: (
mediaTimestamp: number,
@@ -478,6 +549,17 @@ export const audioIteratorManager = ({
}
if (audioBufferIterator && !audioBufferIterator.isDestroyed()) {
+ // When looping, queued nodes carry continuous timestamps that don't
+ // wrap at loop boundaries. Map the new time into that continuous
+ // frame so it can be compared against the queued period.
+ const timeToCheck =
+ loop && currentAnchor
+ ? anchorToContinuousTime({
+ anchor: currentAnchor,
+ unloopedTimeInSeconds: unloopedNewTime,
+ playbackRate: localPlaybackRate,
+ })
+ : newTime;
const queuedPeriod = audioBufferIterator.getQueuedPeriod();
// If there is a missing period, but we'd have no chance to schedule nodes,
// then let's not bother. Let's just leave the gap.
@@ -492,7 +574,7 @@ export const audioIteratorManager = ({
}
: null;
const currentTimeIsAlreadyQueued = isAlreadyQueued(
- newTime,
+ timeToCheck,
queuedPeriodMinusLatency,
);
if (currentTimeIsAlreadyQueued) {
@@ -503,8 +585,8 @@ export const audioIteratorManager = ({
const currentIteratorTimestamp = audioBufferIterator.guessNextTimestamp();
if (
- currentIteratorTimestamp < newTime &&
- Math.abs(currentIteratorTimestamp - newTime) < 1
+ currentIteratorTimestamp < timeToCheck &&
+ Math.abs(currentIteratorTimestamp - timeToCheck) < 1
) {
processNext();
// iterator is less than 1 second behind, we will just let it run
@@ -516,6 +598,7 @@ export const audioIteratorManager = ({
nonce,
playbackRate,
startFromSecond: newTime,
+ unloopedStartFromSecond: unloopedNewTime,
scheduleAudioNode,
getTargetTime,
logLevel,
@@ -530,9 +613,14 @@ export const audioIteratorManager = ({
return {
startAudioIterator,
getAudioBufferIterator: () => audioBufferIterator,
+ getCurrentAnchor: () => currentAnchor,
destroyIterator: () => {
audioBufferIterator?.destroy();
audioBufferIterator = null;
+ // Drop the anchor together with the iterator it described, so
+ // getCurrentAnchor() cannot hand out a stale mapping (from a previous
+ // rate/trim) during the window before a new iterator is started.
+ currentAnchor = null;
unblockCurrentDelayHandle();
},
seek,
diff --git a/packages/media/src/audio/audio-preview-iterator.ts b/packages/media/src/audio/audio-preview-iterator.ts
index a05583e463..58db251f24 100644
--- a/packages/media/src/audio/audio-preview-iterator.ts
+++ b/packages/media/src/audio/audio-preview-iterator.ts
@@ -1,6 +1,4 @@
-import type {AudioBufferSink} from 'mediabunny';
-import type {LogLevel} from 'remotion';
-import {makeIteratorWithPriming} from '../make-iterator-with-priming';
+import type {AudioBufferSlice} from '../make-iterator-with-priming';
export const HEALTHY_BUFFER_THRESHOLD_SECONDS = 1;
export const ALLOWED_GLOBAL_TIME_ANCHOR_SHIFT = 0.1;
@@ -9,6 +7,7 @@ export type QueuedNode = {
node: AudioBufferSourceNode;
timestamp: number;
buffer: AudioBuffer;
+ sourceDurationInSeconds: number;
scheduledTime: number;
playbackRate: number;
scheduledAtAnchor: number;
@@ -19,43 +18,29 @@ export type QueuedPeriod = {
until: number;
};
+export type MakeAudioIteratorOptions = {
+ startFromSecond: number;
+ iterator: AsyncGenerator<AudioBufferSlice, void, unknown>;
+ unscheduleAudioNode: (node: AudioBufferSourceNode) => void;
+};
+
export const makeAudioIterator = ({
startFromSecond,
- maximumTimestamp,
- audioSink,
- loop,
- playbackRate,
- sequenceDurationInSeconds,
+ iterator,
unscheduleAudioNode,
-}: {
- startFromSecond: number;
- maximumTimestamp: number;
- logLevel: LogLevel;
- audioSink: AudioBufferSink;
- loop: boolean;
- playbackRate: number;
- sequenceDurationInSeconds: number;
- unscheduleAudioNode: (node: AudioBufferSourceNode) => void;
-}) => {
+}: MakeAudioIteratorOptions) => {
let destroyed = false;
- const iterator = makeIteratorWithPriming({
- audioSink,
- timeToSeek: startFromSecond,
- maximumTimestamp,
- loop,
- playbackRate,
- sequenceDurationInSeconds,
- });
const queuedAudioNodes: QueuedNode[] = [];
let mostRecentTimestamp = -Infinity;
const cleanupAudioQueue = () => {
- for (const node of queuedAudioNodes) {
- unscheduleAudioNode(node.node);
+ for (const {node} of queuedAudioNodes) {
+ unscheduleAudioNode(node);
try {
- node.node.stop();
+ node.stop();
} catch {
- // Node may not have been started
+ // AudioBufferSourceNode.stop() throws if the node was never started.
+ // Cleanup is a safe boundary: it must continue stopping other nodes.
}
}
@@ -68,7 +53,7 @@ export const makeAudioIterator = ({
if (next.value) {
mostRecentTimestamp = Math.max(
mostRecentTimestamp,
- next.value.timestamp + next.value.buffer.duration,
+ next.value.timelineTimestamp + next.value.sourceDurationInSeconds,
);
}
@@ -79,6 +64,9 @@ export const makeAudioIterator = ({
destroy: () => {
cleanupAudioQueue();
destroyed = true;
+ // Returning an async generator can reject if its underlying media input
+ // was disposed. Destruction is fire-and-forget and has no caller to
+ // propagate to, so intentionally consume that teardown-only rejection.
iterator.return().catch(() => undefined);
},
getNextFn,
@@ -86,27 +74,8 @@ export const makeAudioIterator = ({
return destroyed;
},
- addQueuedAudioNode: ({
- node,
- timestamp,
- buffer,
- scheduledTime,
- scheduledAtAnchor,
- }: {
- node: AudioBufferSourceNode;
- timestamp: number;
- buffer: AudioBuffer;
- scheduledTime: number;
- scheduledAtAnchor: number;
- }) => {
- queuedAudioNodes.push({
- node,
- timestamp,
- buffer,
- scheduledTime,
- playbackRate,
- scheduledAtAnchor,
- });
+ addQueuedAudioNode: (queuedNode: QueuedNode) => {
+ queuedAudioNodes.push(queuedNode);
},
guessNextTimestamp: () => {
return !Number.isFinite(mostRecentTimestamp)
@@ -118,7 +87,7 @@ export const makeAudioIterator = ({
let from = Infinity;
for (const node of queuedAudioNodes) {
- until = Math.max(until, node.timestamp + node.buffer.duration);
+ until = Math.max(until, node.timestamp + node.sourceDurationInSeconds);
from = Math.min(from, node.timestamp);
}
diff --git a/packages/media/src/audio/get-scheduled-time.ts b/packages/media/src/audio/get-scheduled-time.ts
index e27f04d9da..da216e3b39 100644
--- a/packages/media/src/audio/get-scheduled-time.ts
+++ b/packages/media/src/audio/get-scheduled-time.ts
@@ -23,29 +23,20 @@ export const getScheduledTime = ({
};
export const getDurationOfNode = ({
- bufferDuration,
- loopSegmentMediaEndTimestamp,
+ sourceDurationInSeconds,
+ sourceOffsetInSeconds,
offset,
- originalUnloopedMediaTimestamp,
}: {
- bufferDuration: number;
- loopSegmentMediaEndTimestamp: number;
+ sourceDurationInSeconds: number;
+ sourceOffsetInSeconds: number;
offset: number;
- originalUnloopedMediaTimestamp: number;
}) => {
- const originalUnloopedMediaEndTime =
- originalUnloopedMediaTimestamp + bufferDuration;
- const needsTrimEnd =
- originalUnloopedMediaEndTime > loopSegmentMediaEndTimestamp;
-
- const durationMinusOffset = bufferDuration - offset;
-
- const duration = needsTrimEnd
- ? durationMinusOffset -
- Math.max(0, originalUnloopedMediaEndTime - loopSegmentMediaEndTimestamp)
- : durationMinusOffset;
-
- return duration;
+ // The iterator already clipped the source slice to the media range. If the
+ // scheduler starts even later, remove only that additional offset.
+ return Math.max(
+ 0,
+ sourceDurationInSeconds - (offset - sourceOffsetInSeconds),
+ );
};
export const getTrimStartForAudioNode = ({
@@ -53,11 +44,13 @@ export const getTrimStartForAudioNode = ({
targetTime,
sequenceStartTime,
combinedPlaybackRate,
+ sourceStartOffsetInSeconds,
}: {
mediaTimestamp: number;
targetTime: number;
sequenceStartTime: number;
combinedPlaybackRate: number;
+ sourceStartOffsetInSeconds: number;
}) => {
const needsTrimStart = mediaTimestamp < sequenceStartTime;
@@ -67,5 +60,7 @@ export const getTrimStartForAudioNode = ({
const offsetBecauseOfTooLate =
targetTime < 0 ? -targetTime * combinedPlaybackRate : 0;
- return offsetBecauseOfTrim + offsetBecauseOfTooLate;
+ return (
+ sourceStartOffsetInSeconds + offsetBecauseOfTrim + offsetBecauseOfTooLate
+ );
};
diff --git a/packages/media/src/make-iterator-with-priming.ts b/packages/media/src/make-iterator-with-priming.ts
index 6a0694daff..d51d4ffae1 100644
--- a/packages/media/src/make-iterator-with-priming.ts
+++ b/packages/media/src/make-iterator-with-priming.ts
@@ -2,102 +2,119 @@ import type {AudioBufferSink, WrappedAudioBuffer} from 'mediabunny';
const AUDIO_PRIMING_SECONDS = 0.5;
-export type BufferWithMediaTimestamp = {
+export type AudioBufferSlice = {
buffer: WrappedAudioBuffer;
- timestamp: number;
+ // Position where the audible slice begins on the continuous timeline.
+ timelineTimestamp: number;
+ // Range to play from the underlying AudioBuffer.
+ sourceOffsetInSeconds: number;
+ sourceDurationInSeconds: number;
};
-async function* makeIteratorWithPrimingInner(
- audioSink: AudioBufferSink,
- timeToSeek: number,
- maximumTimestamp: number,
-): AsyncGenerator<BufferWithMediaTimestamp, void, unknown> {
+export async function* makeIteratorWithPriming({
+ audioSink,
+ timeToSeek,
+ maximumTimestamp,
+}: {
+ audioSink: AudioBufferSink;
+ timeToSeek: number;
+ maximumTimestamp: number;
+}): AsyncGenerator<AudioBufferSlice, void, unknown> {
const primingStart = Math.max(0, timeToSeek - AUDIO_PRIMING_SECONDS);
const iterator = audioSink.buffers(primingStart, maximumTimestamp);
for await (const buffer of iterator) {
- if (buffer.timestamp + buffer.duration <= timeToSeek) {
+ const sourceStart = Math.max(buffer.timestamp, timeToSeek);
+ const sourceEnd = Math.min(
+ buffer.timestamp + buffer.duration,
+ maximumTimestamp,
+ );
+
+ if (sourceEnd <= sourceStart) {
continue;
}
yield {
buffer,
- timestamp: buffer.timestamp,
+ timelineTimestamp: sourceStart,
+ sourceOffsetInSeconds: sourceStart - buffer.timestamp,
+ sourceDurationInSeconds: sourceEnd - sourceStart,
};
}
}
-async function* makeLoopingIterator({
- audioSink,
- segmentStartInSeconds,
- segmentEndInSeconds,
- playbackRate,
- sequenceDurationInSeconds,
-}: {
+type MakeLoopingIteratorOptions = {
audioSink: AudioBufferSink;
- segmentStartInSeconds: number;
+ seekTimeInSeconds: number;
+ loopStartInSeconds: number;
segmentEndInSeconds: number;
- playbackRate: number;
- sequenceDurationInSeconds: number;
-}): AsyncGenerator<BufferWithMediaTimestamp, void, unknown> {
- const duration = segmentEndInSeconds - segmentStartInSeconds;
- let iteration = 0;
+ maximumContinuousTimestamp: number;
+};
+
+export async function* makeLoopingIterator({
+ audioSink,
+ seekTimeInSeconds,
+ loopStartInSeconds,
+ segmentEndInSeconds,
+ maximumContinuousTimestamp,
+}: MakeLoopingIteratorOptions): AsyncGenerator<
+ AudioBufferSlice,
+ void,
+ unknown
+> {
+ if (segmentEndInSeconds <= loopStartInSeconds) {
+ throw new Error(
+ `Cannot loop audio over an empty range (${loopStartInSeconds} to ${segmentEndInSeconds})`,
+ );
+ }
+
+ // The first pass starts at the seek position, every following pass replays
+ // the full loop segment from its start. Timestamps continue monotonically
+ // across passes so that chunks belonging to a later loop iteration can be
+ // scheduled ahead of the loop boundary.
+ let passStartInSeconds = seekTimeInSeconds;
+ let passBaseTimestamp = seekTimeInSeconds;
- let broken = false;
while (true) {
- for await (const item of makeIteratorWithPrimingInner(
+ let yieldedInPass = false;
+ for await (const item of makeIteratorWithPriming({
audioSink,
- segmentStartInSeconds,
- segmentEndInSeconds,
- )) {
- const timestamp = item.timestamp + iteration * duration;
+ timeToSeek: passStartInSeconds,
+ maximumTimestamp: segmentEndInSeconds,
+ })) {
+ yieldedInPass = true;
+ const timelineTimestamp =
+ passBaseTimestamp + (item.timelineTimestamp - passStartInSeconds);
+ const sourceDurationInSeconds = Math.min(
+ item.sourceDurationInSeconds,
+ maximumContinuousTimestamp - timelineTimestamp,
+ );
- const endTimestamp =
- duration * iteration +
- (item.timestamp - segmentStartInSeconds + item.buffer.duration);
- if (endTimestamp > sequenceDurationInSeconds * playbackRate) {
- broken = true;
- break;
+ if (sourceDurationInSeconds <= 0) {
+ return;
}
yield {
- buffer: item.buffer,
- timestamp,
+ ...item,
+ timelineTimestamp,
+ sourceDurationInSeconds,
};
+
+ if (
+ timelineTimestamp + sourceDurationInSeconds >=
+ maximumContinuousTimestamp
+ ) {
+ return;
+ }
}
- if (broken) {
- break;
+ if (!yieldedInPass) {
+ throw new Error(
+ `Audio loop pass from ${passStartInSeconds} to ${segmentEndInSeconds} yielded no buffers`,
+ );
}
- iteration++;
+ passBaseTimestamp += segmentEndInSeconds - passStartInSeconds;
+ passStartInSeconds = loopStartInSeconds;
}
}
-
-export const makeIteratorWithPriming = ({
- audioSink,
- timeToSeek,
- maximumTimestamp,
- loop,
- playbackRate,
- sequenceDurationInSeconds,
-}: {
- audioSink: AudioBufferSink;
- timeToSeek: number;
- maximumTimestamp: number;
- loop: boolean;
- playbackRate: number;
- sequenceDurationInSeconds: number;
-}): AsyncGenerator<BufferWithMediaTimestamp, void, unknown> => {
- if (loop) {
- return makeLoopingIterator({
- audioSink,
- segmentStartInSeconds: timeToSeek,
- segmentEndInSeconds: maximumTimestamp,
- playbackRate,
- sequenceDurationInSeconds,
- });
- }
-
- return makeIteratorWithPrimingInner(audioSink, timeToSeek, maximumTimestamp);
-};
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index efd8f01bd7..5e3e224ae0 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -8,6 +8,7 @@ import type {
} from 'remotion';
import {Internals} from 'remotion';
import {
+ anchorToContinuousTime,
audioIteratorManager,
type AudioIteratorManager,
} from './audio-iterator-manager';
@@ -401,6 +402,7 @@ export class MediaPlayer {
nonce,
playbackRate: this.playbackRate * this.globalPlaybackRate,
startFromSecond: startTime,
+ unloopedStartFromSecond: startTimeUnresolved,
scheduleAudioNode: this.scheduleAudioNode,
getTargetTime: this.getTargetTime,
logLevel: this.logLevel,
@@ -449,11 +451,18 @@ export class MediaPlayer {
}
}
- private seekToWithQueue = async (newTime: number) => {
+ private seekToWithQueue = async (
+ newTime: number,
+ unloopedNewTime: number,
+ ) => {
const nonce = this.nonceManager.createAsyncOperation();
await this.seekPromiseChain;
- this.seekPromiseChain = this.seekToDoNotCallDirectly(newTime, nonce);
+ this.seekPromiseChain = this.seekToDoNotCallDirectly(
+ newTime,
+ unloopedNewTime,
+ nonce,
+ );
await this.seekPromiseChain;
};
@@ -464,11 +473,12 @@ export class MediaPlayer {
throw new Error(`should have asserted that the time is not null`);
}
- await this.seekToWithQueue(newTime);
+ await this.seekToWithQueue(newTime, time);
}
private async seekToDoNotCallDirectly(
newTime: number,
+ unloopedNewTime: number,
nonce: Nonce,
): Promise<void> {
if (nonce.isStale()) {
@@ -483,8 +493,10 @@ export class MediaPlayer {
}),
this.audioIteratorManager?.seek({
newTime,
+ unloopedNewTime,
nonce,
playbackRate: this.playbackRate * this.globalPlaybackRate,
+ localPlaybackRate: this.playbackRate,
getTargetTime: this.getTargetTime,
logLevel: this.logLevel,
loop: this.loop,
@@ -695,7 +707,23 @@ export class MediaPlayer {
const timeInSeconds = globalTime - this.sequenceOffset;
- const localTime = this.getTrimmedTime(timeInSeconds);
+ // When looping, the audio iterator emits timestamps that continue
+ // monotonically across loop iterations, while the looped media time
+ // wraps at every iteration. Comparing against the wrapped time would
+ // schedule each chunk one loop duration later per iteration. Use the
+ // anchor established when the iterator was started to convert the
+ // current time into the same continuous frame instead.
+ const anchor = this.loop
+ ? (this.audioIteratorManager?.getCurrentAnchor() ?? null)
+ : null;
+
+ const localTime = anchor
+ ? anchorToContinuousTime({
+ anchor,
+ unloopedTimeInSeconds: timeInSeconds,
+ playbackRate: this.playbackRate,
+ })
+ : this.getTrimmedTime(timeInSeconds);
if (localTime === null) {
return null;
@@ -712,6 +740,8 @@ export class MediaPlayer {
node: AudioBufferSourceNode,
mediaTimestamp: number,
originalUnloopedMediaTimestamp: number,
+ sourceOffsetInSeconds: number,
+ sourceDurationInSeconds: number,
): ScheduleAudioNodeResult => {
if (!this.sharedAudioContext) {
throw new Error('Shared audio context not found');
@@ -734,20 +764,19 @@ export class MediaPlayer {
}
const sequenceStartTime = this.getStartTime();
- const loopSegmentMediaEndTimestamp = this.getLoopSegmentMediaEndTimestamp();
const offset = getTrimStartForAudioNode({
mediaTimestamp,
targetTime,
sequenceStartTime,
combinedPlaybackRate,
+ sourceStartOffsetInSeconds: sourceOffsetInSeconds,
});
const duration = getDurationOfNode({
- bufferDuration: node.buffer?.duration ?? 0,
- loopSegmentMediaEndTimestamp,
+ sourceDurationInSeconds,
+ sourceOffsetInSeconds,
offset,
- originalUnloopedMediaTimestamp,
});
const scheduledTime = getScheduledTime({
@@ -760,6 +789,7 @@ export class MediaPlayer {
return this.sharedAudioContext.scheduleAudioNode({
node,
mediaTimestamp,
+ sourceOffset: sourceOffsetInSeconds,
scheduledTime,
duration,
offset,
diff --git a/packages/media/src/test/audio-cleanup-on-seek.test.ts b/packages/media/src/test/audio-cleanup-on-seek.test.ts
index a65959bbfc..72f445846e 100644
--- a/packages/media/src/test/audio-cleanup-on-seek.test.ts
+++ b/packages/media/src/test/audio-cleanup-on-seek.test.ts
@@ -1,21 +1,6 @@
-import {ALL_FORMATS, AudioBufferSink, Input, UrlSource} from 'mediabunny';
import {expect, test} from 'vitest';
import {makeAudioIterator} from '../audio/audio-preview-iterator';
-
-const makeCache = async () => {
- const input = new Input({
- source: new UrlSource('https://remotion.media/video.mp4'),
- formats: ALL_FORMATS,
- });
- const audioTrack = await input.getPrimaryAudioTrack();
- if (!audioTrack) {
- throw new Error('No audio track found');
- }
-
- const audioBufferSink = new AudioBufferSink(audioTrack);
-
- return audioBufferSink;
-};
+import type {AudioBufferSlice} from '../make-iterator-with-priming';
const makeMockNode = () => {
let stopped = false;
@@ -37,44 +22,43 @@ const makeMockBuffer = (duration: number) => {
} as unknown as AudioBuffer;
};
-test('destroy should stop nodes when the audio anchor changed (seek to different position)', async () => {
- const audioBufferSink = await makeCache();
+async function* makeEmptySource(): AsyncGenerator<
+ AudioBufferSlice,
+ void,
+ unknown
+> {}
+
+test('destroy should stop nodes when the audio anchor changed (seek to different position)', () => {
const iterator = makeAudioIterator({
startFromSecond: 0,
- maximumTimestamp: Infinity,
- audioSink: audioBufferSink,
- logLevel: 'info',
- loop: false,
- playbackRate: 1,
- sequenceDurationInSeconds: 10,
+ iterator: makeEmptySource(),
unscheduleAudioNode: () => {},
});
const mock1 = makeMockNode();
const mock2 = makeMockNode();
- // Add nodes scheduled at anchor 0
iterator.addQueuedAudioNode({
node: mock1.node,
timestamp: 0,
buffer: makeMockBuffer(0.021),
+ sourceDurationInSeconds: 0.021,
scheduledTime: 0.1,
+ playbackRate: 1,
scheduledAtAnchor: 0,
});
iterator.addQueuedAudioNode({
node: mock2.node,
timestamp: 0.021,
buffer: makeMockBuffer(0.021),
+ sourceDurationInSeconds: 0.021,
scheduledTime: 0.121,
+ playbackRate: 1,
scheduledAtAnchor: 0,
});
- // Destroy with a DIFFERENT anchor (simulating a seek happened)
- // Even though nodes are "already playing" (currentTime > scheduledTime),
- // they should be stopped because the anchor changed
iterator.destroy();
- // Nodes SHOULD be stopped because the anchor changed (seek happened)
expect(mock1.wasStopped()).toBe(true);
expect(mock2.wasStopped()).toBe(true);
});
diff --git a/packages/media/src/test/audio-iterator.test.ts b/packages/media/src/test/audio-iterator.test.ts
index b2b20e0efb..c9bcd1e3e3 100644
--- a/packages/media/src/test/audio-iterator.test.ts
+++ b/packages/media/src/test/audio-iterator.test.ts
@@ -1,20 +1,31 @@
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
import type {ScheduleAudioNodeResult} from 'remotion';
import {expect, test} from 'vitest';
-import {audioIteratorManager} from '../audio-iterator-manager';
+import {
+ anchorToContinuousTime,
+ audioIteratorManager,
+} from '../audio-iterator-manager';
import {makeNonceManager} from '../nonce-manager';
const prepare = async (options?: {
fps?: number;
playbackRate?: number;
+ localPlaybackRate?: number;
mediaEndTimestamp?: number;
sequenceEndTimestamp?: number;
+ sequenceDurationInSeconds?: number;
+ startTime?: number;
+ loop?: boolean;
}) => {
const {
fps = 30,
playbackRate = 1,
+ localPlaybackRate = playbackRate,
mediaEndTimestamp = Infinity,
sequenceEndTimestamp = Infinity,
+ sequenceDurationInSeconds = 10,
+ startTime = 0,
+ loop = false,
} = options ?? {};
const input = new Input({
source: new UrlSource('https://remotion.media/video.mp4'),
@@ -56,8 +67,8 @@ const prepare = async (options?: {
},
getMediaEndTimestamp: () => mediaEndTimestamp,
getSequenceEndTimestamp: () => sequenceEndTimestamp,
- getSequenceDurationInSeconds: () => 10,
- getStartTime: () => 0,
+ getSequenceDurationInSeconds: () => sequenceDurationInSeconds,
+ getStartTime: () => startTime,
initialMuted: false,
drawDebugOverlay: () => {},
initialPlaybackRate: 1,
@@ -65,18 +76,23 @@ const prepare = async (options?: {
initialTrimAfter: undefined,
initialSequenceOffset: 0,
initialSequenceDurationInFrames: 10,
- initialLoop: false,
+ initialLoop: loop,
initialFps: 30,
});
const scheduledChunks: number[] = [];
+ const scheduledStartOffsets: number[] = [];
const waiters: {count: number; resolve: () => void}[] = [];
const scheduleAudioNode = (
_node: AudioBufferSourceNode,
mediaTimestamp: number,
+ _originalUnloopedMediaTimestamp: number,
+ sourceOffsetInSeconds: number,
+ _sourceDurationInSeconds: number,
): ScheduleAudioNodeResult => {
scheduledChunks.push(mediaTimestamp);
+ scheduledStartOffsets.push(sourceOffsetInSeconds);
for (let i = waiters.length - 1; i >= 0; i--) {
if (scheduledChunks.length >= waiters[i].count) {
waiters[i].resolve();
@@ -90,15 +106,23 @@ const prepare = async (options?: {
};
};
- const seek = ({time}: {time: number}) => {
+ const seek = ({
+ time,
+ unloopedTime = time,
+ }: {
+ time: number;
+ unloopedTime?: number;
+ }) => {
manager.seek({
newTime: time,
+ unloopedNewTime: unloopedTime,
scheduleAudioNode,
nonce: makeNonceManager().createAsyncOperation(),
playbackRate,
+ localPlaybackRate,
getTargetTime: (mediaTimestamp: number) => mediaTimestamp,
logLevel: 'info',
- loop: false,
+ loop,
trimBefore: undefined,
trimAfter: undefined,
sequenceOffset: 0,
@@ -113,11 +137,34 @@ const prepare = async (options?: {
manager,
fps,
scheduledChunks,
+ scheduledStartOffsets,
seek,
audioContextCurrentTime,
};
};
+test('anchor maps unlooped time using the local playback rate', () => {
+ const anchor = {
+ unloopedStartInSeconds: 10,
+ mediaStartInSeconds: 4,
+ };
+
+ expect(
+ anchorToContinuousTime({
+ anchor,
+ unloopedTimeInSeconds: 12,
+ playbackRate: 0.5,
+ }),
+ ).toBe(5);
+ expect(
+ anchorToContinuousTime({
+ anchor,
+ unloopedTimeInSeconds: 12,
+ playbackRate: 2,
+ }),
+ ).toBe(8);
+});
+
test('media player should work', async () => {
const {manager, scheduledChunks, seek, audioContextCurrentTime} =
await prepare();
@@ -128,9 +175,7 @@ test('media player should work', async () => {
});
await manager.waitForNScheduledNodes(3);
- expect(scheduledChunks).toEqual([
- 9.941333333333333, 9.962666666666667, 9.984,
- ]);
+ expect(scheduledChunks).toEqual([9.96, 9.962666666666667, 9.984]);
scheduledChunks.length = 0;
seek({
@@ -177,7 +222,7 @@ test('should not create too many iterators when the audio ends', async () => {
const created = manager.getAudioIteratorsCreated();
expect(created).toBe(1);
- expect(scheduledChunks).toEqual([9.962666666666667, 9.984]);
+ expect(scheduledChunks).toEqual([9.97, 9.984]);
});
test('should not create too many iterators when the audio ends (variant)', async () => {
@@ -198,7 +243,7 @@ test('should not create too many iterators when the audio ends (variant)', async
const created = manager.getAudioIteratorsCreated();
expect(created).toBe(1);
- expect(scheduledChunks).toEqual([9.962666666666667, 9.984]);
+ expect(scheduledChunks).toEqual([9.97, 9.984]);
});
test('should create more iterators when seeking ', async () => {
@@ -224,7 +269,7 @@ test('should create more iterators when seeking ', async () => {
expect(created).toBe(2);
expect(scheduledChunks).toEqual([
- 1.984, 2.005333333333333, 2.026666666666667, 2.048, 2.0693333333333332,
+ 2, 2.005333333333333, 2.026666666666667, 2.048, 2.0693333333333332,
2.0906666666666665,
]);
});
@@ -268,6 +313,42 @@ test('should not schedule duplicate chunks with playbackRate=0.5', async () => {
expect(scheduledChunks.length).toBe(uniqueChunks.length);
});
+test('looping keeps continuous timestamps and reuses the iterator after a wrapped seek', async () => {
+ const {manager, seek, scheduledChunks, scheduledStartOffsets} = await prepare(
+ {
+ playbackRate: 1,
+ localPlaybackRate: 0.5,
+ mediaEndTimestamp: 0.1,
+ sequenceDurationInSeconds: 1,
+ loop: true,
+ },
+ );
+
+ seek({time: 0.08, unloopedTime: 0.08});
+ await manager.waitForNScheduledNodes(8);
+
+ expect(scheduledChunks.length).toBeGreaterThanOrEqual(8);
+ for (let i = 1; i < scheduledChunks.length; i++) {
+ expect(scheduledChunks[i]).toBeGreaterThan(scheduledChunks[i - 1]);
+ }
+
+ expect(scheduledChunks.some((timestamp) => timestamp >= 0.1)).toBe(true);
+ expect(scheduledStartOffsets.some((offset) => offset > 0)).toBe(true);
+
+ // The wrapped media time differs, but the unlooped time maps into the
+ // already queued continuous period using localPlaybackRate.
+ seek({time: 0, unloopedTime: 0.12});
+ expect(manager.getAudioIteratorsCreated()).toBe(1);
+
+ // Seeking by exactly one loop duration produces the same wrapped media time
+ // and must not recreate the iterator either.
+ seek({time: 0, unloopedTime: 0.22});
+ expect(manager.getAudioIteratorsCreated()).toBe(1);
+
+ manager.destroyIterator();
+ expect(manager.getCurrentAnchor()).toBe(null);
+});
+
test('should not decode + schedule audio chunks beyond the end time', async () => {
const endTime = 0.5;
const fps = 30;
diff --git a/packages/media/src/test/looping-audio-timestamps.test.ts b/packages/media/src/test/looping-audio-timestamps.test.ts
new file mode 100644
index 0000000000..0015d24abd
--- /dev/null
+++ b/packages/media/src/test/looping-audio-timestamps.test.ts
@@ -0,0 +1,201 @@
+import type {AudioBufferSink, WrappedAudioBuffer} from 'mediabunny';
+import {expect, test} from 'vitest';
+import {
+ getDurationOfNode,
+ getTrimStartForAudioNode,
+} from '../audio/get-scheduled-time';
+import {
+ makeIteratorWithPriming,
+ makeLoopingIterator,
+} from '../make-iterator-with-priming';
+
+const CHUNK_DURATION = 1;
+
+// Yields 1-second chunks like a real AudioBufferSink, including the chunk
+// that straddles the requested start time.
+const makeMockAudioSink = (mediaDurationInSeconds: number) => {
+ return {
+ async *buffers(start: number, end: number) {
+ const firstChunk = Math.max(0, Math.floor(start));
+ const lastChunk = Math.min(mediaDurationInSeconds, end);
+ for (let i = firstChunk; i < lastChunk; i += CHUNK_DURATION) {
+ yield {
+ timestamp: i,
+ duration: CHUNK_DURATION,
+ buffer: null,
+ } as unknown as WrappedAudioBuffer;
+ }
+ },
+ } as unknown as AudioBufferSink;
+};
+
+const collect = async (
+ iterator: AsyncGenerator<
+ {buffer: WrappedAudioBuffer; timelineTimestamp: number},
+ void,
+ unknown
+ >,
+ count: number,
+) => {
+ const chunks: {timestamp: number; rawTimestamp: number}[] = [];
+ for await (const chunk of iterator) {
+ chunks.push({
+ timestamp: chunk.timelineTimestamp,
+ rawTimestamp: chunk.buffer.timestamp,
+ });
+ if (chunks.length >= count) {
+ break;
+ }
+ }
+
+ return chunks;
+};
+
+// https://github.com/remotion-dev/remotion/issues/8922
+test('looped audio timestamps must continue monotonically across loop iterations', async () => {
+ const iterator = makeLoopingIterator({
+ audioSink: makeMockAudioSink(10),
+ seekTimeInSeconds: 0,
+ segmentEndInSeconds: 10,
+ loopStartInSeconds: 0,
+ maximumContinuousTimestamp: 100,
+ });
+
+ const chunks = await collect(iterator, 30);
+
+ expect(chunks.map((c) => c.timestamp)).toEqual(
+ new Array(30).fill(0).map((_, i) => i),
+ );
+ expect(chunks.map((c) => c.rawTimestamp)).toEqual(
+ new Array(30).fill(0).map((_, i) => i % 10),
+ );
+});
+
+test('seeking into the middle of a loop must replay the full segment on later iterations', async () => {
+ const iterator = makeLoopingIterator({
+ audioSink: makeMockAudioSink(10),
+ seekTimeInSeconds: 4,
+ segmentEndInSeconds: 10,
+ loopStartInSeconds: 0,
+ maximumContinuousTimestamp: 100,
+ });
+
+ const chunks = await collect(iterator, 26);
+
+ expect(chunks.slice(0, 6).map((c) => c.rawTimestamp)).toEqual([
+ 4, 5, 6, 7, 8, 9,
+ ]);
+ expect(chunks.slice(6, 16).map((c) => c.rawTimestamp)).toEqual([
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ ]);
+ expect(chunks.slice(16, 26).map((c) => c.rawTimestamp)).toEqual([
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ ]);
+ expect(chunks.map((c) => c.timestamp)).toEqual(
+ new Array(26).fill(0).map((_, i) => 4 + i),
+ );
+});
+
+test('looped audio with trimBefore must replay the trimmed segment', async () => {
+ const iterator = makeLoopingIterator({
+ audioSink: makeMockAudioSink(10),
+ seekTimeInSeconds: 5,
+ segmentEndInSeconds: 10,
+ loopStartInSeconds: 3,
+ maximumContinuousTimestamp: 100,
+ });
+
+ const chunks = await collect(iterator, 19);
+
+ expect(chunks.map((c) => c.rawTimestamp)).toEqual([
+ 5, 6, 7, 8, 9, 3, 4, 5, 6, 7, 8, 9, 3, 4, 5, 6, 7, 8, 9,
+ ]);
+ expect(chunks.map((c) => c.timestamp)).toEqual(
+ new Array(19).fill(0).map((_, i) => 5 + i),
+ );
+});
+
+test('looping iterator must stop at the manager-provided continuous timestamp', async () => {
+ const iterator = makeLoopingIterator({
+ audioSink: makeMockAudioSink(10),
+ seekTimeInSeconds: 4,
+ segmentEndInSeconds: 10,
+ loopStartInSeconds: 0,
+ // Equivalent to a 3-second sequence at playbackRate=2, calculated by
+ // audioIteratorManager rather than by the source generator.
+ maximumContinuousTimestamp: 10,
+ });
+
+ const chunks = await collect(iterator, 1000);
+ expect(chunks.map((chunk) => chunk.timestamp)).toEqual([4, 5, 6, 7, 8, 9]);
+});
+
+test('one-pass iterator does not wrap', async () => {
+ const iterator = makeIteratorWithPriming({
+ audioSink: makeMockAudioSink(10),
+ timeToSeek: 8,
+ maximumTimestamp: 10,
+ });
+
+ const chunks = await collect(iterator, 1000);
+ expect(chunks.map((chunk) => chunk.rawTimestamp)).toEqual([8, 9]);
+});
+
+test('scheduler trimming is additional to the source slice offset', () => {
+ const sourceOffsetInSeconds = 0.013;
+ const offset = getTrimStartForAudioNode({
+ mediaTimestamp: 3,
+ sequenceStartTime: 3.002,
+ targetTime: -0.003,
+ combinedPlaybackRate: 2,
+ sourceStartOffsetInSeconds: sourceOffsetInSeconds,
+ });
+
+ expect(offset).toBeCloseTo(0.021);
+ expect(
+ getDurationOfNode({
+ sourceDurationInSeconds: 0.03,
+ sourceOffsetInSeconds,
+ offset,
+ }),
+ ).toBeCloseTo(0.022);
+});
+
+test('boundary buffers are represented as source slices on every pass', async () => {
+ const crossingBufferSink = {
+ async *buffers(_start: number, _end: number) {
+ yield {
+ timestamp: 2.987,
+ duration: 0.021,
+ buffer: null,
+ } as unknown as WrappedAudioBuffer;
+ yield {
+ timestamp: 3.008,
+ duration: 0.021,
+ buffer: null,
+ } as unknown as WrappedAudioBuffer;
+ },
+ } as unknown as AudioBufferSink;
+
+ const iterator = makeLoopingIterator({
+ audioSink: crossingBufferSink,
+ seekTimeInSeconds: 3,
+ loopStartInSeconds: 3,
+ segmentEndInSeconds: 3.02,
+ maximumContinuousTimestamp: 3.04,
+ });
+
+ const first = await iterator.next();
+ const second = await iterator.next();
+ const third = await iterator.next();
+
+ expect(first.value?.timelineTimestamp).toBe(3);
+ expect(first.value?.sourceOffsetInSeconds).toBeCloseTo(0.013);
+ expect(first.value?.sourceDurationInSeconds).toBeCloseTo(0.008);
+ expect(second.value?.timelineTimestamp).toBeCloseTo(3.008);
+ expect(second.value?.sourceOffsetInSeconds).toBe(0);
+ expect(second.value?.sourceDurationInSeconds).toBeCloseTo(0.012);
+ expect(third.value?.timelineTimestamp).toBeCloseTo(3.02);
+ expect(third.value?.sourceOffsetInSeconds).toBeCloseTo(0.013);
+ expect(third.value?.sourceDurationInSeconds).toBeCloseTo(0.008);
+});
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 b64124716b..7e3b3827cf 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
@@ -125,6 +125,7 @@ test('same goes for audio', async () => {
nonce: nonceManager.createAsyncOperation(),
playbackRate: 1,
startFromSecond: 0.06671494248275864,
+ unloopedStartFromSecond: 0.06671494248275864,
scheduleAudioNode: () => ({
type: 'started',
scheduledTime: 0,
@@ -139,8 +140,10 @@ test('same goes for audio', async () => {
await manager.waitForNScheduledNodes(2);
manager.seek({
newTime: 0.10007241372413796,
+ unloopedNewTime: 0.10007241372413796,
nonce: nonceManager.createAsyncOperation(),
playbackRate: 1,
+ localPlaybackRate: 1,
scheduleAudioNode: () => ({
type: 'started',
scheduledTime: 0,