@remotion/media 4.0.379 → 4.0.380

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/audio/audio-for-preview.js +1 -1
  2. package/dist/audio/audio-preview-iterator.js +27 -4
  3. package/dist/audio/props.d.ts +1 -0
  4. package/dist/audio-for-rendering.d.ts +3 -0
  5. package/dist/audio-for-rendering.js +94 -0
  6. package/dist/audio.d.ts +3 -0
  7. package/dist/audio.js +60 -0
  8. package/dist/audiodata-to-array.d.ts +0 -0
  9. package/dist/audiodata-to-array.js +1 -0
  10. package/dist/convert-audiodata/data-types.d.ts +1 -0
  11. package/dist/convert-audiodata/data-types.js +22 -0
  12. package/dist/convert-audiodata/is-planar-format.d.ts +1 -0
  13. package/dist/convert-audiodata/is-planar-format.js +3 -0
  14. package/dist/convert-audiodata/log-audiodata.d.ts +1 -0
  15. package/dist/convert-audiodata/log-audiodata.js +8 -0
  16. package/dist/convert-audiodata/trim-audiodata.d.ts +0 -0
  17. package/dist/convert-audiodata/trim-audiodata.js +1 -0
  18. package/dist/deserialized-audiodata.d.ts +15 -0
  19. package/dist/deserialized-audiodata.js +26 -0
  20. package/dist/esm/index.mjs +28 -4
  21. package/dist/extract-audio.d.ts +7 -0
  22. package/dist/extract-audio.js +98 -0
  23. package/dist/extract-frame-via-broadcast-channel.d.ts +15 -0
  24. package/dist/extract-frame-via-broadcast-channel.js +104 -0
  25. package/dist/extract-frame.d.ts +27 -0
  26. package/dist/extract-frame.js +21 -0
  27. package/dist/extrct-audio.d.ts +7 -0
  28. package/dist/extrct-audio.js +94 -0
  29. package/dist/get-frames-since-keyframe.d.ts +22 -0
  30. package/dist/get-frames-since-keyframe.js +41 -0
  31. package/dist/keyframe-bank.d.ts +25 -0
  32. package/dist/keyframe-bank.js +120 -0
  33. package/dist/keyframe-manager.d.ts +23 -0
  34. package/dist/keyframe-manager.js +170 -0
  35. package/dist/log.d.ts +10 -0
  36. package/dist/log.js +33 -0
  37. package/dist/new-video-for-rendering.d.ts +3 -0
  38. package/dist/new-video-for-rendering.js +108 -0
  39. package/dist/new-video.d.ts +3 -0
  40. package/dist/new-video.js +37 -0
  41. package/dist/props.d.ts +29 -0
  42. package/dist/props.js +1 -0
  43. package/dist/remember-actual-matroska-timestamps.d.ts +4 -0
  44. package/dist/remember-actual-matroska-timestamps.js +19 -0
  45. package/dist/serialize-videoframe.d.ts +0 -0
  46. package/dist/serialize-videoframe.js +1 -0
  47. package/dist/video/media-player.d.ts +62 -0
  48. package/dist/video/media-player.js +361 -0
  49. package/dist/video/new-video-for-preview.d.ts +10 -0
  50. package/dist/video/new-video-for-preview.js +108 -0
  51. package/dist/video/props.d.ts +1 -0
  52. package/dist/video/timeout-utils.d.ts +2 -0
  53. package/dist/video/timeout-utils.js +18 -0
  54. package/dist/video-extraction/media-player.d.ts +64 -0
  55. package/dist/video-extraction/media-player.js +501 -0
  56. package/dist/video-extraction/new-video-for-preview.d.ts +10 -0
  57. package/dist/video-extraction/new-video-for-preview.js +114 -0
  58. package/dist/video-for-rendering.d.ts +3 -0
  59. package/dist/video-for-rendering.js +108 -0
  60. package/dist/video.d.ts +3 -0
  61. package/dist/video.js +37 -0
  62. package/package.json +3 -3
@@ -0,0 +1,108 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useContext, useLayoutEffect, useMemo, useRef, useState, } from 'react';
3
+ import { cancelRender, Internals, useCurrentFrame, useDelayRender, useRemotionEnvironment, } from 'remotion';
4
+ import { extractFrameViaBroadcastChannel } from './extract-frame-via-broadcast-channel';
5
+ export const VideoForRendering = ({ volume: volumeProp, playbackRate, src, muted, loopVolumeCurveBehavior, delayRenderRetries, delayRenderTimeoutInMilliseconds,
6
+ // call when a frame of the video, i.e. frame drawn on canvas
7
+ onVideoFrame, logLevel = window.remotion_logLevel, }) => {
8
+ const absoluteFrame = Internals.useTimelinePosition();
9
+ const videoConfig = Internals.useUnsafeVideoConfig();
10
+ const canvasRef = useRef(null);
11
+ const { registerRenderAsset, unregisterRenderAsset } = useContext(Internals.RenderAssetManager);
12
+ const frame = useCurrentFrame();
13
+ const volumePropsFrame = Internals.useFrameForVolumeProp(loopVolumeCurveBehavior ?? 'repeat');
14
+ const environment = useRemotionEnvironment();
15
+ const [id] = useState(() => `${Math.random()}`.replace('0.', ''));
16
+ if (!videoConfig) {
17
+ throw new Error('No video config found');
18
+ }
19
+ if (!src) {
20
+ throw new TypeError('No `src` was passed to <Video>.');
21
+ }
22
+ const volume = Internals.evaluateVolume({
23
+ volume: volumeProp,
24
+ frame: volumePropsFrame,
25
+ mediaVolume: 1,
26
+ });
27
+ Internals.warnAboutTooHighVolume(volume);
28
+ const shouldRenderAudio = useMemo(() => {
29
+ if (!window.remotion_audioEnabled) {
30
+ return false;
31
+ }
32
+ if (muted) {
33
+ return false;
34
+ }
35
+ if (volume <= 0) {
36
+ return false;
37
+ }
38
+ return true;
39
+ }, [muted, volume]);
40
+ const { fps } = videoConfig;
41
+ const { delayRender, continueRender } = useDelayRender();
42
+ useLayoutEffect(() => {
43
+ if (!canvasRef.current) {
44
+ return;
45
+ }
46
+ const actualFps = playbackRate ? fps / playbackRate : fps;
47
+ const timestamp = frame / actualFps;
48
+ const durationInSeconds = 1 / actualFps;
49
+ const newHandle = delayRender(`Extracting frame number ${frame}`, {
50
+ retries: delayRenderRetries ?? undefined,
51
+ timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
52
+ });
53
+ extractFrameViaBroadcastChannel({
54
+ src,
55
+ timeInSeconds: timestamp,
56
+ durationInSeconds,
57
+ logLevel: logLevel ?? 'info',
58
+ shouldRenderAudio,
59
+ isClientSideRendering: environment.isClientSideRendering,
60
+ })
61
+ .then(({ frame: imageBitmap, audio }) => {
62
+ if (!imageBitmap) {
63
+ cancelRender(new Error('No video frame found'));
64
+ }
65
+ onVideoFrame?.(imageBitmap);
66
+ canvasRef.current?.getContext('2d')?.drawImage(imageBitmap, 0, 0);
67
+ imageBitmap.close();
68
+ if (audio) {
69
+ registerRenderAsset({
70
+ type: 'inline-audio',
71
+ id,
72
+ audio: Array.from(audio.data),
73
+ sampleRate: audio.sampleRate,
74
+ numberOfChannels: audio.numberOfChannels,
75
+ frame: absoluteFrame,
76
+ timestamp: audio.timestamp,
77
+ duration: (audio.numberOfFrames / audio.sampleRate) * 1000000,
78
+ });
79
+ }
80
+ continueRender(newHandle);
81
+ })
82
+ .catch((error) => {
83
+ cancelRender(error);
84
+ });
85
+ return () => {
86
+ continueRender(newHandle);
87
+ unregisterRenderAsset(id);
88
+ };
89
+ }, [
90
+ absoluteFrame,
91
+ continueRender,
92
+ delayRender,
93
+ delayRenderRetries,
94
+ delayRenderTimeoutInMilliseconds,
95
+ environment.isClientSideRendering,
96
+ fps,
97
+ frame,
98
+ id,
99
+ logLevel,
100
+ onVideoFrame,
101
+ playbackRate,
102
+ registerRenderAsset,
103
+ shouldRenderAudio,
104
+ src,
105
+ unregisterRenderAsset,
106
+ ]);
107
+ return (_jsx("canvas", { ref: canvasRef, width: videoConfig.width, height: videoConfig.height }));
108
+ };
@@ -0,0 +1,3 @@
1
+ import React from 'react';
2
+ import type { VideoProps } from './props';
3
+ export declare const Video: React.FC<VideoProps>;
@@ -0,0 +1,37 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useCallback } from 'react';
3
+ import { Internals, Sequence, useRemotionEnvironment } from 'remotion';
4
+ import { VideoForRendering } from './new-video-for-rendering';
5
+ const { validateMediaTrimProps, resolveTrimProps, validateMediaProps, VideoForPreview, } = Internals;
6
+ export const Video = (props) => {
7
+ // Should only destruct `startFrom` and `endAt` from props,
8
+ // rest gets drilled down
9
+ const { trimBefore, trimAfter, name, pauseWhenBuffering, stack, showInTimeline, ...otherProps } = props;
10
+ const environment = useRemotionEnvironment();
11
+ const onDuration = useCallback(() => undefined, []);
12
+ if (typeof props.src !== 'string') {
13
+ throw new TypeError(`The \`<Video>\` tag requires a string for \`src\`, but got ${JSON.stringify(props.src)} instead.`);
14
+ }
15
+ validateMediaTrimProps({
16
+ startFrom: undefined,
17
+ endAt: undefined,
18
+ trimBefore,
19
+ trimAfter,
20
+ });
21
+ const { trimBeforeValue, trimAfterValue } = resolveTrimProps({
22
+ startFrom: undefined,
23
+ endAt: undefined,
24
+ trimBefore,
25
+ trimAfter,
26
+ });
27
+ if (typeof trimBeforeValue !== 'undefined' ||
28
+ typeof trimAfterValue !== 'undefined') {
29
+ return (_jsx(Sequence, { layout: "none", from: 0 - (trimBeforeValue ?? 0), showInTimeline: false, durationInFrames: trimAfterValue, name: name, children: _jsx(Video, { pauseWhenBuffering: pauseWhenBuffering ?? false, ...otherProps }) }));
30
+ }
31
+ validateMediaProps(props, 'Video');
32
+ if (environment.isRendering) {
33
+ return _jsx(VideoForRendering, { ...otherProps });
34
+ }
35
+ const { onAutoPlayError, onVideoFrame, crossOrigin, delayRenderRetries, delayRenderTimeoutInMilliseconds, ...propsForPreview } = otherProps;
36
+ return (_jsx(VideoForPreview, { _remotionInternalStack: stack ?? null, _remotionInternalNativeLoopPassed: false, onDuration: onDuration, onlyWarnForMediaSeekingError: true, pauseWhenBuffering: pauseWhenBuffering ?? false, showInTimeline: showInTimeline ?? true, onAutoPlayError: onAutoPlayError ?? undefined, onVideoFrame: onVideoFrame ?? null, crossOrigin: crossOrigin, ...propsForPreview }));
37
+ };
@@ -0,0 +1,29 @@
1
+ import type { LoopVolumeCurveBehavior, VolumeProp } from 'remotion';
2
+ import type { LogLevel } from './log';
3
+ export type AudioProps = {
4
+ src: string;
5
+ trimBefore?: number;
6
+ trimAfter?: number;
7
+ volume?: VolumeProp;
8
+ loopVolumeCurveBehavior?: LoopVolumeCurveBehavior;
9
+ name?: string;
10
+ pauseWhenBuffering?: boolean;
11
+ showInTimeline?: boolean;
12
+ onAutoPlayError?: null | (() => void);
13
+ playbackRate?: number;
14
+ muted?: boolean;
15
+ delayRenderRetries?: number;
16
+ delayRenderTimeoutInMilliseconds?: number;
17
+ crossOrigin?: '' | 'anonymous' | 'use-credentials';
18
+ style?: React.CSSProperties;
19
+ onError?: (err: Error) => void;
20
+ useWebAudioApi?: boolean;
21
+ acceptableTimeShiftInSeconds?: number;
22
+ /**
23
+ * @deprecated For internal use only
24
+ */
25
+ stack?: string;
26
+ logLevel?: LogLevel;
27
+ loop?: boolean;
28
+ _remotionInternalNativeLoopPassed?: boolean;
29
+ };
package/dist/props.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ export declare const rememberActualMatroskaTimestamps: (isMatroska: boolean) => {
2
+ observeTimestamp: (startTime: number) => void;
3
+ getRealTimestamp: (observedTimestamp: number) => number | null;
4
+ };
@@ -0,0 +1,19 @@
1
+ export const rememberActualMatroskaTimestamps = (isMatroska) => {
2
+ const observations = [];
3
+ const observeTimestamp = (startTime) => {
4
+ if (!isMatroska) {
5
+ return;
6
+ }
7
+ observations.push(startTime);
8
+ };
9
+ const getRealTimestamp = (observedTimestamp) => {
10
+ if (!isMatroska) {
11
+ return observedTimestamp;
12
+ }
13
+ return (observations.find((observation) => Math.abs(observedTimestamp - observation) < 0.001) ?? null);
14
+ };
15
+ return {
16
+ observeTimestamp,
17
+ getRealTimestamp,
18
+ };
19
+ };
File without changes
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,62 @@
1
+ import type { LogLevel } from 'remotion';
2
+ export declare const SEEK_THRESHOLD = 0.05;
3
+ export declare class MediaPlayer {
4
+ private canvas;
5
+ private context;
6
+ private src;
7
+ private logLevel;
8
+ private canvasSink;
9
+ private videoFrameIterator;
10
+ private nextFrame;
11
+ private audioSink;
12
+ private audioBufferIterator;
13
+ private queuedAudioNodes;
14
+ private gainNode;
15
+ private sharedAudioContext;
16
+ private audioSyncAnchor;
17
+ private playing;
18
+ private animationFrameId;
19
+ private videoAsyncId;
20
+ private initialized;
21
+ private totalDuration;
22
+ private isBuffering;
23
+ private onBufferingChangeCallback?;
24
+ private audioBufferHealth;
25
+ private audioIteratorStarted;
26
+ private readonly HEALTHY_BUFER_THRESHOLD_SECONDS;
27
+ constructor({ canvas, src, logLevel, sharedAudioContext, }: {
28
+ canvas: HTMLCanvasElement;
29
+ src: string;
30
+ logLevel: LogLevel;
31
+ sharedAudioContext: AudioContext;
32
+ });
33
+ private input;
34
+ private isReady;
35
+ private hasAudio;
36
+ private isCurrentlyBuffering;
37
+ initialize(startTime?: number): Promise<void>;
38
+ private cleanupAudioQueue;
39
+ private cleanAudioIteratorAndNodes;
40
+ seekTo(time: number): Promise<void>;
41
+ play(): Promise<void>;
42
+ pause(): void;
43
+ dispose(): void;
44
+ private getPlaybackTime;
45
+ private scheduleAudioChunk;
46
+ onBufferingChange(callback: (isBuffering: boolean) => void): void;
47
+ private canRenderVideo;
48
+ private startRenderLoop;
49
+ private stopRenderLoop;
50
+ private render;
51
+ private shouldRenderFrame;
52
+ private drawCurrentFrame;
53
+ private startAudioIterator;
54
+ private startVideoIterator;
55
+ private updateNextFrame;
56
+ private bufferingStartedAtMs;
57
+ private minBufferingTimeoutMs;
58
+ private setBufferingState;
59
+ private maybeResumeFromBuffering;
60
+ private maybeForceResumeFromBuffering;
61
+ private runAudioIterator;
62
+ }
@@ -0,0 +1,361 @@
1
+ import { ALL_FORMATS, AudioBufferSink, CanvasSink, Input, UrlSource, } from 'mediabunny';
2
+ import { Internals } from 'remotion';
3
+ import { sleep, withTimeout } from './timeout-utils';
4
+ export const SEEK_THRESHOLD = 0.05;
5
+ export class MediaPlayer {
6
+ constructor({ canvas, src, logLevel, sharedAudioContext, }) {
7
+ this.canvasSink = null;
8
+ this.videoFrameIterator = null;
9
+ this.nextFrame = null;
10
+ this.audioSink = null;
11
+ this.audioBufferIterator = null;
12
+ this.queuedAudioNodes = new Set();
13
+ this.gainNode = null;
14
+ // audioDelay = mediaTimestamp + audioSyncAnchor - sharedAudioContext.currentTime
15
+ this.audioSyncAnchor = 0;
16
+ this.playing = false;
17
+ this.animationFrameId = null;
18
+ this.videoAsyncId = 0;
19
+ this.initialized = false;
20
+ this.totalDuration = 0;
21
+ // for remotion buffer state
22
+ this.isBuffering = false;
23
+ this.audioBufferHealth = 0;
24
+ this.audioIteratorStarted = false;
25
+ this.HEALTHY_BUFER_THRESHOLD_SECONDS = 1;
26
+ this.input = null;
27
+ this.render = () => {
28
+ if (this.isBuffering) {
29
+ this.maybeForceResumeFromBuffering();
30
+ }
31
+ if (this.shouldRenderFrame()) {
32
+ this.drawCurrentFrame();
33
+ }
34
+ if (this.playing) {
35
+ this.animationFrameId = requestAnimationFrame(this.render);
36
+ }
37
+ else {
38
+ this.animationFrameId = null;
39
+ }
40
+ };
41
+ this.startAudioIterator = async (timeToSeek) => {
42
+ if (!this.hasAudio())
43
+ return;
44
+ // Clean up existing audio iterator
45
+ await this.audioBufferIterator?.return();
46
+ this.audioIteratorStarted = false;
47
+ this.audioBufferHealth = 0;
48
+ try {
49
+ this.audioBufferIterator = this.audioSink.buffers(timeToSeek);
50
+ this.runAudioIterator();
51
+ }
52
+ catch (error) {
53
+ Internals.Log.error({ logLevel: this.logLevel, tag: '@remotion/media' }, '[MediaPlayer] Failed to start audio iterator', error);
54
+ }
55
+ };
56
+ this.startVideoIterator = async (timeToSeek) => {
57
+ if (!this.canvasSink) {
58
+ return;
59
+ }
60
+ this.videoAsyncId++;
61
+ const currentAsyncId = this.videoAsyncId;
62
+ await this.videoFrameIterator?.return();
63
+ this.videoFrameIterator = this.canvasSink.canvases(timeToSeek);
64
+ try {
65
+ const firstFrame = (await this.videoFrameIterator.next()).value ?? null;
66
+ const secondFrame = (await this.videoFrameIterator.next()).value ?? null;
67
+ if (currentAsyncId !== this.videoAsyncId) {
68
+ return;
69
+ }
70
+ if (firstFrame) {
71
+ Internals.Log.trace({ logLevel: this.logLevel, tag: '@remotion/media' }, `[MediaPlayer] Drew initial frame ${firstFrame.timestamp.toFixed(3)}s`);
72
+ this.context.drawImage(firstFrame.canvas, 0, 0);
73
+ }
74
+ this.nextFrame = secondFrame ?? null;
75
+ if (secondFrame) {
76
+ Internals.Log.trace({ logLevel: this.logLevel, tag: '@remotion/media' }, `[MediaPlayer] Buffered next frame ${secondFrame.timestamp.toFixed(3)}s`);
77
+ }
78
+ }
79
+ catch (error) {
80
+ Internals.Log.error({ logLevel: this.logLevel, tag: '@remotion/media' }, '[MediaPlayer] Failed to start video iterator', error);
81
+ }
82
+ };
83
+ this.updateNextFrame = async () => {
84
+ if (!this.videoFrameIterator) {
85
+ return;
86
+ }
87
+ try {
88
+ while (true) {
89
+ const newNextFrame = (await this.videoFrameIterator.next()).value ?? null;
90
+ if (!newNextFrame) {
91
+ break;
92
+ }
93
+ if (newNextFrame.timestamp <= this.getPlaybackTime()) {
94
+ continue;
95
+ }
96
+ else {
97
+ this.nextFrame = newNextFrame;
98
+ Internals.Log.trace({ logLevel: this.logLevel, tag: '@remotion/media' }, `[MediaPlayer] Buffered next frame ${newNextFrame.timestamp.toFixed(3)}s`);
99
+ break;
100
+ }
101
+ }
102
+ }
103
+ catch (error) {
104
+ Internals.Log.error({ logLevel: this.logLevel, tag: '@remotion/media' }, '[MediaPlayer] Failed to update next frame', error);
105
+ }
106
+ };
107
+ this.bufferingStartedAtMs = null;
108
+ this.minBufferingTimeoutMs = 500;
109
+ this.runAudioIterator = async () => {
110
+ if (!this.hasAudio() || !this.audioBufferIterator)
111
+ return;
112
+ try {
113
+ let totalBufferDuration = 0;
114
+ let isFirstBuffer = true;
115
+ this.audioIteratorStarted = true;
116
+ while (true) {
117
+ const BUFFERING_TIMEOUT_MS = 50;
118
+ let result;
119
+ try {
120
+ result = await withTimeout(this.audioBufferIterator.next(), BUFFERING_TIMEOUT_MS, 'Iterator timeout');
121
+ }
122
+ catch {
123
+ this.setBufferingState(true);
124
+ await sleep(10);
125
+ continue;
126
+ }
127
+ if (result.done || !result.value) {
128
+ break;
129
+ }
130
+ const { buffer, timestamp, duration } = result.value;
131
+ totalBufferDuration += duration;
132
+ this.audioBufferHealth = Math.max(0, totalBufferDuration);
133
+ this.maybeResumeFromBuffering(totalBufferDuration);
134
+ if (this.playing) {
135
+ if (isFirstBuffer) {
136
+ this.audioSyncAnchor =
137
+ this.sharedAudioContext.currentTime - timestamp;
138
+ isFirstBuffer = false;
139
+ }
140
+ this.scheduleAudioChunk(buffer, timestamp);
141
+ }
142
+ if (timestamp - this.getPlaybackTime() >= 1) {
143
+ await new Promise((resolve) => {
144
+ const check = () => {
145
+ if (timestamp - this.getPlaybackTime() < 1) {
146
+ resolve();
147
+ }
148
+ else {
149
+ requestAnimationFrame(check);
150
+ }
151
+ };
152
+ check();
153
+ });
154
+ }
155
+ }
156
+ }
157
+ catch (error) {
158
+ Internals.Log.error({ logLevel: this.logLevel, tag: '@remotion/media' }, '[MediaPlayer] Failed to run audio iterator', error);
159
+ }
160
+ };
161
+ this.canvas = canvas;
162
+ this.src = src;
163
+ this.logLevel = logLevel ?? 'info';
164
+ this.sharedAudioContext = sharedAudioContext;
165
+ const context = canvas.getContext('2d', {
166
+ alpha: false,
167
+ desynchronized: true,
168
+ });
169
+ if (!context) {
170
+ throw new Error('Could not get 2D context from canvas');
171
+ }
172
+ this.context = context;
173
+ }
174
+ isReady() {
175
+ return this.initialized && Boolean(this.sharedAudioContext);
176
+ }
177
+ hasAudio() {
178
+ return Boolean(this.audioSink && this.sharedAudioContext && this.gainNode);
179
+ }
180
+ isCurrentlyBuffering() {
181
+ return this.isBuffering && Boolean(this.bufferingStartedAtMs);
182
+ }
183
+ async initialize(startTime = 0) {
184
+ try {
185
+ const urlSource = new UrlSource(this.src);
186
+ const input = new Input({
187
+ source: urlSource,
188
+ formats: ALL_FORMATS,
189
+ });
190
+ this.input = input;
191
+ this.totalDuration = await input.computeDuration();
192
+ const videoTrack = await input.getPrimaryVideoTrack();
193
+ const audioTrack = await input.getPrimaryAudioTrack();
194
+ if (!videoTrack && !audioTrack) {
195
+ throw new Error(`No video or audio track found for ${this.src}`);
196
+ }
197
+ if (videoTrack) {
198
+ this.canvasSink = new CanvasSink(videoTrack, {
199
+ poolSize: 2,
200
+ fit: 'contain',
201
+ });
202
+ this.canvas.width = videoTrack.displayWidth;
203
+ this.canvas.height = videoTrack.displayHeight;
204
+ }
205
+ if (audioTrack && this.sharedAudioContext) {
206
+ this.audioSink = new AudioBufferSink(audioTrack);
207
+ this.gainNode = this.sharedAudioContext.createGain();
208
+ this.gainNode.connect(this.sharedAudioContext.destination);
209
+ }
210
+ if (this.sharedAudioContext) {
211
+ this.audioSyncAnchor = this.sharedAudioContext.currentTime - startTime;
212
+ }
213
+ this.initialized = true;
214
+ await this.startAudioIterator(startTime);
215
+ await this.startVideoIterator(startTime);
216
+ this.startRenderLoop();
217
+ }
218
+ catch (error) {
219
+ Internals.Log.error({ logLevel: this.logLevel, tag: '@remotion/media' }, '[MediaPlayer] Failed to initialize', error);
220
+ throw error;
221
+ }
222
+ }
223
+ cleanupAudioQueue() {
224
+ for (const node of this.queuedAudioNodes) {
225
+ node.stop();
226
+ }
227
+ this.queuedAudioNodes.clear();
228
+ }
229
+ async cleanAudioIteratorAndNodes() {
230
+ await this.audioBufferIterator?.return();
231
+ this.audioBufferIterator = null;
232
+ this.audioIteratorStarted = false;
233
+ this.audioBufferHealth = 0;
234
+ this.cleanupAudioQueue();
235
+ }
236
+ async seekTo(time) {
237
+ if (!this.isReady())
238
+ return;
239
+ const newTime = Math.max(0, Math.min(time, this.totalDuration));
240
+ const currentPlaybackTime = this.getPlaybackTime();
241
+ const isSignificantSeek = Math.abs(newTime - currentPlaybackTime) > SEEK_THRESHOLD;
242
+ if (isSignificantSeek) {
243
+ this.audioSyncAnchor = this.sharedAudioContext.currentTime - newTime;
244
+ if (this.audioSink) {
245
+ await this.cleanAudioIteratorAndNodes();
246
+ }
247
+ await this.startAudioIterator(newTime);
248
+ await this.startVideoIterator(newTime);
249
+ }
250
+ if (!this.playing) {
251
+ this.render();
252
+ }
253
+ }
254
+ async play() {
255
+ if (!this.isReady())
256
+ return;
257
+ if (!this.playing) {
258
+ if (this.sharedAudioContext.state === 'suspended') {
259
+ await this.sharedAudioContext.resume();
260
+ }
261
+ this.playing = true;
262
+ this.startRenderLoop();
263
+ }
264
+ }
265
+ pause() {
266
+ this.playing = false;
267
+ this.cleanupAudioQueue();
268
+ this.stopRenderLoop();
269
+ }
270
+ dispose() {
271
+ this.input?.dispose();
272
+ this.stopRenderLoop();
273
+ this.videoFrameIterator?.return();
274
+ this.cleanAudioIteratorAndNodes();
275
+ this.videoAsyncId++;
276
+ }
277
+ getPlaybackTime() {
278
+ return this.sharedAudioContext.currentTime - this.audioSyncAnchor;
279
+ }
280
+ scheduleAudioChunk(buffer, mediaTimestamp) {
281
+ const targetTime = mediaTimestamp + this.audioSyncAnchor;
282
+ const delay = targetTime - this.sharedAudioContext.currentTime;
283
+ const node = this.sharedAudioContext.createBufferSource();
284
+ node.buffer = buffer;
285
+ node.connect(this.gainNode);
286
+ if (delay >= 0) {
287
+ node.start(targetTime);
288
+ }
289
+ else {
290
+ node.start(this.sharedAudioContext.currentTime, -delay);
291
+ }
292
+ this.queuedAudioNodes.add(node);
293
+ node.onended = () => this.queuedAudioNodes.delete(node);
294
+ }
295
+ onBufferingChange(callback) {
296
+ this.onBufferingChangeCallback = callback;
297
+ }
298
+ canRenderVideo() {
299
+ return (this.audioIteratorStarted &&
300
+ this.audioBufferHealth >= this.HEALTHY_BUFER_THRESHOLD_SECONDS);
301
+ }
302
+ startRenderLoop() {
303
+ if (this.animationFrameId !== null) {
304
+ return;
305
+ }
306
+ this.render();
307
+ }
308
+ stopRenderLoop() {
309
+ if (this.animationFrameId !== null) {
310
+ cancelAnimationFrame(this.animationFrameId);
311
+ this.animationFrameId = null;
312
+ }
313
+ }
314
+ shouldRenderFrame() {
315
+ return (!this.isBuffering &&
316
+ this.canRenderVideo() &&
317
+ this.nextFrame !== null &&
318
+ this.nextFrame.timestamp <= this.getPlaybackTime());
319
+ }
320
+ drawCurrentFrame() {
321
+ this.context.drawImage(this.nextFrame.canvas, 0, 0);
322
+ this.nextFrame = null;
323
+ this.updateNextFrame();
324
+ }
325
+ setBufferingState(isBuffering) {
326
+ if (this.isBuffering !== isBuffering) {
327
+ this.isBuffering = isBuffering;
328
+ if (isBuffering) {
329
+ this.bufferingStartedAtMs = performance.now();
330
+ this.onBufferingChangeCallback?.(true);
331
+ }
332
+ else {
333
+ this.bufferingStartedAtMs = null;
334
+ this.onBufferingChangeCallback?.(false);
335
+ }
336
+ }
337
+ }
338
+ maybeResumeFromBuffering(currentBufferDuration) {
339
+ if (!this.isCurrentlyBuffering())
340
+ return;
341
+ const now = performance.now();
342
+ const bufferingDuration = now - this.bufferingStartedAtMs;
343
+ const minTimeElapsed = bufferingDuration >= this.minBufferingTimeoutMs;
344
+ const bufferHealthy = currentBufferDuration >= this.HEALTHY_BUFER_THRESHOLD_SECONDS;
345
+ if (minTimeElapsed && bufferHealthy) {
346
+ Internals.Log.trace({ logLevel: this.logLevel, tag: '@remotion/media' }, `[MediaPlayer] Resuming from buffering after ${bufferingDuration}ms - buffer recovered`);
347
+ this.setBufferingState(false);
348
+ }
349
+ }
350
+ maybeForceResumeFromBuffering() {
351
+ if (!this.isCurrentlyBuffering())
352
+ return;
353
+ const now = performance.now();
354
+ const bufferingDuration = now - this.bufferingStartedAtMs;
355
+ const forceTimeout = bufferingDuration > this.minBufferingTimeoutMs * 10;
356
+ if (forceTimeout) {
357
+ Internals.Log.trace({ logLevel: this.logLevel, tag: '@remotion/media' }, `[MediaPlayer] Force resuming from buffering after ${bufferingDuration}ms`);
358
+ this.setBufferingState(false);
359
+ }
360
+ }
361
+ }
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ import type { LogLevel } from 'remotion';
3
+ type NewVideoForPreviewProps = {
4
+ readonly src: string;
5
+ readonly style?: React.CSSProperties;
6
+ readonly playbackRate?: number;
7
+ readonly logLevel?: LogLevel;
8
+ };
9
+ export declare const NewVideoForPreview: React.FC<NewVideoForPreviewProps>;
10
+ export {};