Skip to content

🎥 Make videos programmatically with React

27.1 KB
Raw Blame
import type {Input} from 'mediabunny';
import type {
	EffectChainState,
	EffectDefinitionAndStack,
	LogLevel,
	ScheduleAudioNodeResult,
	useBufferState,
} from 'remotion';
import {Internals} from 'remotion';
import {
	anchorToContinuousTime,
	audioIteratorManager,
	type AudioIteratorManager,
} from './audio-iterator-manager';
import {
	getDurationOfNode,
	getScheduledTime,
	getTrimStartForAudioNode,
} from './audio/get-scheduled-time';
import {processNext} from './audio/sort-by-priority';
import {drawPreviewOverlay} from './debug-overlay/preview-overlay';
import {acquireSharedInput} from './get-shared-input';
import {calculateEndTime, getTimeInSeconds} from './get-time-in-seconds';
import {resolveAudioTrack} from './helpers/resolve-audio-track';
import {isNetworkError} from './is-type-of-error';
import type {Nonce, NonceManager} from './nonce-manager';
import {makeNonceManager} from './nonce-manager';
import {PremountAwareDelayPlayback} from './premount-aware-delay-playback';
import type {MediaRequestInit} from './request-init';
import type {SharedAudioContextForMediaPlayer} from './shared-audio-context-for-media-player';
import type {VideoIteratorManager} from './video-iterator-manager';
import {videoIteratorManager} from './video-iterator-manager';
import type {MaxCanvasSinkFrameSize} from './video/props';

export type MediaPlayerInitResult =
	| {type: 'success'; durationInSeconds: number}
	| {type: 'unknown-container-format'; error: Error}
	| {type: 'cannot-decode'; error: Error}
	| {type: 'cannot-decode-prores'}
	| {type: 'network-error'; error: Error}
	| {type: 'no-tracks'}
	| {type: 'disposed'};

export type MediaSeekIntent =
	| {readonly revision: number; readonly playing: boolean}
	// An internal resync after media configuration changes, not a timeline seek.
	// Invalidate the satisfied revision so the next video request cannot be
	// mistaken for continuous playback. This does not always restart the iterator.
	| 'discontinuity'
	| null;

export class MediaPlayer {
	private tagType: 'audio' | 'video';
	private canvas: HTMLCanvasElement | OffscreenCanvas | null;
	private context:
		| OffscreenCanvasRenderingContext2D
		| CanvasRenderingContext2D
		| null;

	private src: string;
	private logLevel: LogLevel;
	private playbackRate: number;
	private toneFrequency: number;
	private globalPlaybackRate: number;
	private audioStreamIndex: number | null;

	private sharedAudioContext: SharedAudioContextForMediaPlayer | null;

	audioIteratorManager: AudioIteratorManager | null = null;
	private muted = false;
	private unsupportedAudioError: Error | null = null;
	videoIteratorManager: VideoIteratorManager | null = null;

	private playing = false;
	private lastSeekIntent: MediaSeekIntent = null;
	private satisfiedSeekRevision: number | null = null;
	private loop = false;
	private fps: number;

	private trimBefore: number | undefined;
	private trimAfter: number | undefined;
	private sequenceDurationInFrames: number;
	private sequenceOffset: number;

	private totalDuration: number | undefined;

	private debugOverlay = false;

	private nonceManager: NonceManager;

	private onVideoFrameCallback: null | ((frame: CanvasImageSource) => void) =
		null;

	private getEffects: () => EffectDefinitionAndStack<unknown>[];
	private getEffectChainState: (
		width: number,
		height: number,
	) => EffectChainState | null;

	private maxCanvasSinkFrameSize: MaxCanvasSinkFrameSize | null;

	private initializationPromise: Promise<MediaPlayerInitResult> | null = null;

	private premountAwareDelayPlayback: PremountAwareDelayPlayback;
	private seekPromiseChain: Promise<unknown> = Promise.resolve();
	private terminalError: Error | null = null;
	private onError: ((error: Error) => void) | null;

	constructor({
		canvas,
		src,
		logLevel,
		sharedAudioContext,
		loop,
		trimBefore,
		trimAfter,
		playbackRate,
		toneFrequency,
		globalPlaybackRate,
		audioStreamIndex,
		fps,
		debugOverlay,
		bufferState,
		isPremounting,
		isPostmounting,
		durationInFrames,
		onVideoFrameCallback,
		playing,
		sequenceOffset,
		credentials,
		requestInit,
		tagType,
		getEffects,
		getEffectChainState,
		maxCanvasSinkFrameSize,
		onError,
	}: {
		canvas: HTMLCanvasElement | OffscreenCanvas | null;
		src: string;
		logLevel: LogLevel;
		sharedAudioContext: SharedAudioContextForMediaPlayer | null;
		loop: boolean;
		trimBefore: number | undefined;
		trimAfter: number | undefined;
		playbackRate: number;
		toneFrequency: number;
		globalPlaybackRate: number;
		audioStreamIndex: number | null;
		fps: number;
		debugOverlay: boolean;
		bufferState: ReturnType<typeof useBufferState>;
		isPremounting: boolean;
		isPostmounting: boolean;
		durationInFrames: number;
		onVideoFrameCallback: null | ((frame: CanvasImageSource) => void);
		playing: boolean;
		sequenceOffset: number;
		credentials: RequestCredentials | undefined;
		requestInit: MediaRequestInit | undefined;
		tagType: 'audio' | 'video';
		getEffects: () => EffectDefinitionAndStack<unknown>[];
		getEffectChainState: (
			width: number,
			height: number,
		) => EffectChainState | null;
		maxCanvasSinkFrameSize: MaxCanvasSinkFrameSize | null;
		onError: ((error: Error) => void) | null;
	}) {
		this.canvas = canvas ?? null;
		this.src = src;
		this.logLevel = logLevel;
		this.sharedAudioContext = sharedAudioContext;
		this.playbackRate = playbackRate;
		this.toneFrequency = toneFrequency;
		this.globalPlaybackRate = globalPlaybackRate;
		this.loop = loop;
		this.trimBefore = trimBefore;
		this.trimAfter = trimAfter;
		this.audioStreamIndex = audioStreamIndex;
		this.fps = fps;
		this.debugOverlay = debugOverlay;
		this.premountAwareDelayPlayback = new PremountAwareDelayPlayback({
			bufferState,
			isPremounting,
			isPostmounting,
		});
		this.sequenceDurationInFrames = durationInFrames;
		this.nonceManager = makeNonceManager();
		this.onVideoFrameCallback = onVideoFrameCallback;
		this.playing = playing;
		this.sequenceOffset = sequenceOffset;
		// Reuse a shared, reference-counted Input per (src, credentials,
		// requestInit) so mounting a new range does not re-parse the container or
		// cold-seek — the byte cache and demuxer state stay warm across ranges.
		const {input, getDuration, release} = acquireSharedInput({
			src: this.src,
			credentials,
			requestInit,
			logLevel,
		});
		this.input = input;
		this.getDuration = getDuration;
		this.releaseInput = release;
		this.tagType = tagType;
		this.getEffects = getEffects;
		this.getEffectChainState = getEffectChainState;
		this.maxCanvasSinkFrameSize = maxCanvasSinkFrameSize;
		this.onError = onError;

		if (canvas) {
			const context = canvas.getContext('2d', {
				alpha: true,
			}) as OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D | null;

			if (!context) {
				throw new Error('Could not get 2D context from canvas');
			}

			this.context = context;
		} else {
			this.context = null;
		}
	}

	private input: Input;
	private getDuration: () => Promise<number>;
	private releaseInput: () => void;
	// Per-player disposal flag. The Input is now shared and reference counted, so
	// `this.input.disposed` no longer tells us whether THIS player was disposed
	// (the Input stays alive while other players hold it). This flag tracks our
	// own lifecycle instead.
	private disposed = false;

	private isDisposalError(): boolean {
		return this.disposed || this.input.disposed === true;
	}

	private reportTerminalError(error: Error): void {
		if (this.terminalError || this.isDisposalError()) {
			return;
		}

		this.terminalError = error;
		this.playing = false;
		this.audioIteratorManager?.destroyIterator();
		this.videoIteratorManager?.destroy();
		this.onError?.(error);
	}

	public initialize(
		startTimeUnresolved: number,
		initialMuted: boolean,
		initialVolume: number,
	): Promise<MediaPlayerInitResult> {
		this.muted = initialMuted;
		const promise = this._initialize(
			startTimeUnresolved,
			initialMuted,
			initialVolume,
		);
		this.initializationPromise = promise;
		this.seekPromiseChain = promise;
		return promise;
	}

	private getStartTime(): number {
		return (this.trimBefore ?? 0) / this.fps;
	}

	private getSequenceEndTimestamp(): number {
		// Cap at the media time corresponding to the end of the sequence
		return (
			(this.sequenceDurationInFrames / this.fps) * this.playbackRate +
			this.getStartTime()
		);
	}

	private getSequenceDurationInSeconds(): number {
		return this.sequenceDurationInFrames / this.fps;
	}

	private getMediaEndTimestamp(): number {
		return calculateEndTime({
			mediaDurationInSeconds: this.totalDuration!,
			ifNoMediaDuration: 'fail',
			src: this.src,
			trimAfter: this.trimAfter,
			trimBefore: this.trimBefore,
			fps: this.fps,
		});
	}

	private getLoopSegmentMediaEndTimestamp(): number {
		return Math.min(
			this.getMediaEndTimestamp(),
			this.getSequenceEndTimestamp(),
		);
	}

	private async _initialize(
		startTimeUnresolved: number,
		initialMuted: boolean,
		initialVolume: number,
	): Promise<MediaPlayerInitResult> {
		using _ = this.delayPlaybackHandleIfNotPremounting();
		try {
			if (this.isDisposalError()) {
				return {type: 'disposed'};
			}

			try {
				await this.input.getFormat();
			} catch (error) {
				if (this.isDisposalError()) {
					return {type: 'disposed'};
				}

				const err = error as Error;

				if (isNetworkError(err)) {
					throw error;
				}

				Internals.Log.error(
					{logLevel: this.logLevel, tag: '@remotion/media'},
					`[MediaPlayer] Failed to recognize format for ${this.src}`,
					error,
				);

				return {type: 'unknown-container-format', error: err};
			}

			const [durationInSeconds, videoTrack, audioTracks] = await Promise.all([
				this.getDuration(),
				this.input.getPrimaryVideoTrack(),
				this.input.getAudioTracks(),
			]);
			if (this.isDisposalError()) {
				return {type: 'disposed'};
			}

			this.totalDuration = durationInSeconds;

			const audioTrack = await resolveAudioTrack({
				videoTrack,
				audioTracks,
				audioStreamIndex: this.audioStreamIndex,
			});

			if (!videoTrack && !audioTrack) {
				return {type: 'no-tracks'};
			}

			if (videoTrack && this.tagType === 'video') {
				if (await videoTrack.isLive()) {
					throw new Error(
						'Live streams are not currently supported by Remotion. Sorry! Source: ' +
							this.src,
					);
				}

				if (await videoTrack.isRelativeToUnixEpoch()) {
					throw new Error(
						'Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: ' +
							this.src,
					);
				}

				const canDecode = await videoTrack.canDecode();

				if (!canDecode) {
					if (videoTrack.codec === 'prores') {
						return {type: 'cannot-decode-prores'};
					}

					return {
						type: 'cannot-decode',
						error: new Error(
							`Cannot decode video track ${videoTrack.id} (${videoTrack.codec ?? 'unknown codec'}) in ${this.src}.`,
						),
					};
				}

				if (this.isDisposalError()) {
					return {type: 'disposed'};
				}

				this.videoIteratorManager = await videoIteratorManager({
					getIsDisposed: () => this.isDisposalError(),
					videoTrack,
					delayPlaybackHandleIfNotPremounting:
						this.delayPlaybackHandleIfNotPremounting,
					context: this.context,
					canvas: this.canvas,
					getOnVideoFrameCallback: () => this.onVideoFrameCallback,
					logLevel: this.logLevel,
					drawDebugOverlay: this.drawDebugOverlay,
					getLoopSegmentMediaEndTimestamp: () =>
						this.getLoopSegmentMediaEndTimestamp(),
					getStartTime: () => this.getStartTime(),
					getIsLooping: () => this.loop,
					getEffects: this.getEffects,
					getEffectChainState: this.getEffectChainState,
					maxCanvasSinkFrameSize: this.maxCanvasSinkFrameSize,
				});
			}

			if (this.isDisposalError()) {
				return {type: 'disposed'};
			}

			const startTime = this.getTrimmedTime(startTimeUnresolved);

			if (startTime === null) {
				throw new Error(`should have asserted that the time is not null`);
			}

			if (audioTrack && this.sharedAudioContext) {
				if (await audioTrack.isLive()) {
					throw new Error(
						'Live streams are not currently supported by Remotion. Sorry! Source: ' +
							this.src,
					);
				}

				if (await audioTrack.isRelativeToUnixEpoch()) {
					throw new Error(
						'Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: ' +
							this.src,
					);
				}

				const canDecode = await audioTrack.canDecode();
				if (!canDecode && !this.muted) {
					return {
						type: 'cannot-decode',
						error: new Error(
							`Cannot decode audio track ${audioTrack.id} (${audioTrack.codec ?? 'unknown codec'}) in ${this.src}.`,
						),
					};
				}

				if (this.isDisposalError()) {
					return {type: 'disposed'};
				}

				if (canDecode) {
					this.audioIteratorManager = audioIteratorManager({
						audioTrack,
						delayPlaybackHandleIfNotPremounting:
							this.delayPlaybackHandleIfNotPremounting,
						sharedAudioContext: this.sharedAudioContext,
						getMediaEndTimestamp: () => this.getMediaEndTimestamp(),
						getSequenceEndTimestamp: () => this.getSequenceEndTimestamp(),
						getStartTime: () => this.getStartTime(),
						initialMuted,
						initialVolume,
						toneFrequency: this.toneFrequency,
						drawDebugOverlay: this.drawDebugOverlay,
						onError: (error) => this.reportTerminalError(error),
						getSequenceDurationInSeconds: () =>
							this.getSequenceDurationInSeconds(),
					});
				} else {
					// Muted video can draw without an audio decoder. Report the
					// unavailable audio if the caller later requests sound.
					this.unsupportedAudioError = new Error(
						`Cannot decode audio for ${this.src}.`,
					);
				}
			}

			const nonce = this.nonceManager.createAsyncOperation();

			try {
				await Promise.all([
					this.audioIteratorManager
						? this.audioIteratorManager.startAudioIterator({
								nonce,
								playbackRate: this.playbackRate * this.globalPlaybackRate,
								startFromSecond: startTime,
								unloopedStartFromSecond: startTimeUnresolved,
								scheduleAudioNode: this.scheduleAudioNode,
								getTargetTime: this.getTargetTime,
								logLevel: this.logLevel,
								loop: this.loop,
								unscheduleAudioNode:
									this.sharedAudioContext!.unscheduleAudioNode,
								getAudioContextCurrentTimeMockedInTest: () =>
									this.sharedAudioContext!.audioContext.currentTime,
							})
						: Promise.resolve(),
					this.videoIteratorManager
						? this.videoIteratorManager.startVideoIterator(startTime, nonce)
						: Promise.resolve(),
				]);
			} catch (error) {
				if (this.isDisposalError()) {
					return {type: 'disposed'};
				}

				Internals.Log.error(
					{logLevel: this.logLevel, tag: '@remotion/media'},
					'[MediaPlayer] Failed to start audio and video iterators',
					error,
				);
			}

			if (this.isDisposalError()) {
				return {type: 'disposed'};
			}

			return {type: 'success', durationInSeconds};
		} catch (error) {
			const err = error as Error;

			if (isNetworkError(err)) {
				Internals.Log.error(
					{logLevel: this.logLevel, tag: '@remotion/media'},
					`[MediaPlayer] Network/CORS error for ${this.src}`,
					err,
				);
				return {type: 'network-error', error: err};
			}

			Internals.Log.error(
				{logLevel: this.logLevel, tag: '@remotion/media'},
				'[MediaPlayer] Failed to initialize',
				error,
			);
			throw error;
		}
	}

	private seekToWithQueue = async (
		newTime: number,
		unloopedNewTime: number,
		intent: MediaSeekIntent,
	) => {
		const nonce = this.nonceManager.createAsyncOperation();
		await this.seekPromiseChain;

		this.seekPromiseChain = this.seekToDoNotCallDirectly(
			newTime,
			unloopedNewTime,
			nonce,
			intent,
		);
		await this.seekPromiseChain;
	};

	public async seekTo(time: number, intent: MediaSeekIntent): Promise<void> {
		if (this.terminalError || this.isDisposalError()) {
			return;
		}

		const newTime = this.getTrimmedTime(time);

		if (newTime === null) {
			throw new Error(`should have asserted that the time is not null`);
		}

		this.lastSeekIntent = intent;
		if (intent === 'discontinuity') {
			// A mapping change may supersede a queued timeline request.
			this.satisfiedSeekRevision = null;
		}

		await this.seekToWithQueue(newTime, time, intent);
	}

	private async seekToDoNotCallDirectly(
		newTime: number,
		unloopedNewTime: number,
		nonce: Nonce,
		intent: MediaSeekIntent,
	): Promise<void> {
		if (nonce.isStale() || this.terminalError || this.isDisposalError()) {
			return;
		}

		try {
			await Promise.all([
				this.videoIteratorManager?.seek({
					newTime,
					nonce,
					fps: this.fps,
					playbackRate: this.playbackRate,
					isPlaying: this.playing,
					continuousPlayback:
						intent === null
							? null
							: intent !== 'discontinuity' &&
								intent.playing &&
								intent.revision === this.satisfiedSeekRevision,
				}),
				this.audioIteratorManager?.seek({
					newTime,
					unloopedNewTime,
					nonce,
					playbackRate: this.playbackRate * this.globalPlaybackRate,
					localPlaybackRate: this.playbackRate,
					getTargetTime: this.getTargetTime,
					logLevel: this.logLevel,
					loop: this.loop,
					trimBefore: this.trimBefore,
					trimAfter: this.trimAfter,
					sequenceOffset: this.sequenceOffset,
					sequenceDurationInFrames: this.sequenceDurationInFrames,
					fps: this.fps,
					scheduleAudioNode: this.scheduleAudioNode,
					getAudioContextCurrentTimeMockedInTest: () =>
						this.sharedAudioContext!.audioContext.currentTime,
				}),
			]);
			// Superseded work must not consume an explicit seek boundary.
			if (!nonce.isStale() && intent !== null && intent !== 'discontinuity') {
				this.satisfiedSeekRevision = intent.revision;
			}
		} catch (error) {
			if (this.isDisposalError()) {
				return;
			}

			// Seeks are serialized: a newer nonce does not replace the iterator
			// whose read failed. Ignoring the error would leave queued seeks using
			// an exhausted iterator and displaying its last frame indefinitely.
			this.reportTerminalError(error as Error);
		}
	}

	public play(): void {
		if (this.playing || this.terminalError) {
			return;
		}

		this.playing = true;

		this.drawDebugOverlay();
	}

	private delayPlaybackHandleIfNotPremounting = () => {
		return this.premountAwareDelayPlayback.createHandle();
	};

	public pause(): void {
		if (!this.playing) {
			return;
		}

		this.playing = false;
		this.drawDebugOverlay();
	}

	public setMuted(muted: boolean): void {
		this.muted = muted;
		if (!muted && this.unsupportedAudioError) {
			this.reportTerminalError(this.unsupportedAudioError);
			return;
		}

		this.audioIteratorManager?.setMuted(muted);
	}

	public setVolume(volume: number): void {
		if (!this.audioIteratorManager) {
			return;
		}

		this.audioIteratorManager.setVolume(volume);
	}

	private getTrimmedTime(unloopedTimeInSeconds: number): number | null {
		return getTimeInSeconds({
			unloopedTimeInSeconds,
			playbackRate: this.playbackRate,
			loop: this.loop,
			trimBefore: this.trimBefore,
			trimAfter: this.trimAfter,
			mediaDurationInSeconds: this.totalDuration ?? null,
			fps: this.fps,
			ifNoMediaDuration: 'infinity',
			src: this.src,
		});
	}

	public async setTrimRange(
		trimBefore: number | undefined,
		trimAfter: number | undefined,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		if (this.trimBefore !== trimBefore || this.trimAfter !== trimAfter) {
			this.trimBefore = trimBefore;
			this.trimAfter = trimAfter;
			this.audioIteratorManager?.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public setDebugOverlay(debugOverlay: boolean): void {
		this.debugOverlay = debugOverlay;
	}

	public async setPlaybackRate(
		rate: number,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		const previousRate = this.playbackRate;

		if (previousRate !== rate) {
			this.playbackRate = rate;
			this.audioIteratorManager?.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public async setToneFrequency(
		toneFrequency: number,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		if (this.toneFrequency !== toneFrequency) {
			this.toneFrequency = toneFrequency;
			if (!this.audioIteratorManager) {
				return;
			}

			this.audioIteratorManager.setToneFrequency(toneFrequency);
			this.audioIteratorManager.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public async setGlobalPlaybackRate(
		rate: number,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		const previousRate = this.globalPlaybackRate;
		if (previousRate !== rate) {
			this.globalPlaybackRate = rate;
			this.audioIteratorManager?.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public async setFps(
		fps: number,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		const previousFps = this.fps;
		if (previousFps !== fps) {
			this.fps = fps;
			this.audioIteratorManager?.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public setIsPremounting(isPremounting: boolean): void {
		this.premountAwareDelayPlayback.setIsPremounting(isPremounting);
		processNext();
	}

	public setIsPostmounting(isPostmounting: boolean): void {
		this.premountAwareDelayPlayback.setIsPostmounting(isPostmounting);
		processNext();
	}

	public async setLoop(
		loop: boolean,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		const previousLoop = this.loop;
		if (previousLoop !== loop) {
			this.loop = loop;
			this.audioIteratorManager?.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public async setSequenceOffset(
		offset: number,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		const previousOffset = this.sequenceOffset;
		if (previousOffset !== offset) {
			this.sequenceOffset = offset;
			this.audioIteratorManager?.destroyIterator();
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public async setSequenceDurationInFrames(
		sequenceDurationInFrames: number,
		unloopedTimeInSeconds: number,
	): Promise<void> {
		const previousDuration = this.sequenceDurationInFrames;
		if (previousDuration !== sequenceDurationInFrames) {
			this.sequenceDurationInFrames = sequenceDurationInFrames;
			await this.seekTo(unloopedTimeInSeconds, 'discontinuity');
		}
	}

	public async dispose(): Promise<void> {
		// Guard against double-dispose: releasing the shared Input twice would
		// over-decrement its ref count and tear it down while other players still
		// use it.
		if (this.disposed) {
			return;
		}

		this.disposed = true;
		// Cancel pending paints before waiting for initialization to settle.
		this.nonceManager.createAsyncOperation();
		this.videoIteratorManager?.destroy();

		if (this.initializationPromise) {
			try {
				// wait for the init to finished
				// otherwise we might get errors like:
				// Error: Response stream reader stopped unexpectedly before all requested data was read. from UrlSource
				await this.initializationPromise;
			} catch {
				// Ignore initialization errors during disposal
			}
		}

		this.videoIteratorManager?.destroy();
		this.audioIteratorManager?.destroyIterator();
		// Release our reference to the shared Input; it is only disposed once the
		// last MediaPlayer using this src releases it.
		this.releaseInput();
	}

	private getTargetTime = (
		mediaTimestamp: number,
		currentTime: number,
	): number | null => {
		if (!this.sharedAudioContext) {
			throw new Error('Shared audio context not found');
		}

		const globalTime =
			(currentTime - this.sharedAudioContext.audioSyncAnchor.value) *
			this.globalPlaybackRate;

		const timeInSeconds = globalTime - this.sequenceOffset;

		// 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;
		}

		const targetTime =
			(mediaTimestamp - localTime) /
			(this.playbackRate * this.globalPlaybackRate);

		return targetTime;
	};

	private scheduleAudioNode = (
		node: AudioBufferSourceNode,
		mediaTimestamp: number,
		originalUnloopedMediaTimestamp: number,
		sourceOffsetInSeconds: number,
		sourceDurationInSeconds: number,
	): ScheduleAudioNodeResult => {
		if (!this.sharedAudioContext) {
			throw new Error('Shared audio context not found');
		}

		const targetTime = this.getTargetTime(
			mediaTimestamp,
			this.sharedAudioContext.audioContext.currentTime,
		);
		const combinedPlaybackRate = this.playbackRate * this.globalPlaybackRate;
		if (targetTime === null) {
			return {
				type: 'not-started',
				reason:
					'no target for' +
					mediaTimestamp.toFixed(3) +
					',' +
					this.sharedAudioContext.audioContext.currentTime.toFixed(3),
			};
		}

		const sequenceStartTime = this.getStartTime();

		const offset = getTrimStartForAudioNode({
			mediaTimestamp,
			targetTime,
			sequenceStartTime,
			combinedPlaybackRate,
			sourceStartOffsetInSeconds: sourceOffsetInSeconds,
		});

		const duration = getDurationOfNode({
			sourceDurationInSeconds,
			sourceOffsetInSeconds,
			offset,
		});

		const scheduledTime = getScheduledTime({
			mediaTimestamp,
			targetTime,
			sequenceStartTime,
			currentTime: this.sharedAudioContext.audioContext.currentTime,
		});

		return this.sharedAudioContext.scheduleAudioNode({
			node,
			mediaTimestamp,
			sourceOffset: sourceOffsetInSeconds,
			scheduledTime,
			duration,
			offset,
			originalUnloopedMediaTimestamp,
		});
	};

	public setVideoFrameCallback(
		callback: null | ((frame: CanvasImageSource) => void),
	) {
		this.onVideoFrameCallback = callback;
	}

	public async redrawVideoEffects(): Promise<void> {
		await this.videoIteratorManager?.redrawCurrentFrame();
	}

	private drawDebugOverlay = () => {
		if (!this.debugOverlay) return;
		if (this.context && this.canvas) {
			drawPreviewOverlay({
				context: this.context,
				audioTime: this.sharedAudioContext?.audioContext.currentTime ?? null,
				audioContextState: this.sharedAudioContext?.audioContext.state ?? null,
				audioSyncAnchor: this.sharedAudioContext?.audioSyncAnchor ?? null,
				audioIteratorManager: this.audioIteratorManager,
				playing: this.playing,
				videoIteratorManager: this.videoIteratorManager,
				playbackRate: this.playbackRate * this.globalPlaybackRate,
			});
		}
	};

	public audioSyncAnchorChanged = async (unloopedTimeInSeconds: number) => {
		if (!this.audioIteratorManager) {
			return;
		}

		this.audioIteratorManager.destroyIterator();
		// An anchor can change while paused, when no frame update will restart
		// scheduling. Refill the queue against the new anchor immediately.
		// Re-anchoring is not navigation. Preserve the captured revision so an
		// outstanding explicit seek still takes the restart path, but don't let
		// an audio-clock pause turn ordinary video catch-up into a scrub.
		const intent = this.lastSeekIntent;
		await this.seekTo(
			unloopedTimeInSeconds,
			intent !== null && intent !== 'discontinuity'
				? {...intent, playing: true}
				: intent,
		);
	};
}