Skip to content

🎥 Make videos programmatically with React

`extractFrames()` uses `parseMedia()`, new `extractFramesOnWebWorker()` API

JonnyBurgerfaf902d321d4
diff --git a/packages/docs/docs/webcodecs/extract-frames-on-web-worker.mdx b/packages/docs/docs/webcodecs/extract-frames-on-web-worker.mdx
new file mode 100644
index 0000000000..20fd4db193
--- /dev/null
+++ b/packages/docs/docs/webcodecs/extract-frames-on-web-worker.mdx
@@ -0,0 +1,92 @@
+---
+image: /generated/articles-docs-webcodecs-extract-frames-on-web-worker.png
+id: extract-frames-on-web-worker
+title: extractFramesOnWebWorker()
+slug: /webcodecs/extract-frames-on-web-worker
+crumb: '@remotion/webcodecs'
+---
+
+# extractFramesOnWebWorker()<AvailableFrom v="4.0.330"/>
+
+_Part of the [`@remotion/webcodecs`](/docs/webcodecs) package._
+
+Extracts frames from a video at specific timestamps using [`parseMediaOnWebWorker()`](/docs/media-parser/parse-media-on-web-worker).
+
+```tsx twoslash title="Extracting frames"
+import {extractFramesOnWebWorker} from '@remotion/webcodecs/worker';
+
+await extractFramesOnWebWorker({
+ src: 'https://parser.media/video.mp4',
+ timestampsInSeconds: [0, 1, 2, 3, 4],
+ onFrame: (frame) => {
+ console.log(frame);
+ // ^?
+ },
+});
+```
+
+## API
+
+### `src`
+
+A URL or `File`/`Blob`.
+
+If it is a remote URL, it must support CORS.
+
+### `timestampsInSeconds`
+
+An array of timestamps in seconds, or a function that returns a promise resolving to an array of timestamps in seconds based on the video track.
+
+Consider you wanting you to create a filmstrip of a video. You can do this by extracting as many frames as fit in a canvas.
+
+```tsx twoslash title="Extracting as many frames as fit in a canvas"
+import type {ExtractFramesTimestampsInSecondsFn} from '@remotion/webcodecs';
+
+const toSeconds = 10;
+const fromSeconds = 0;
+const canvasWidth = 500;
+const canvasHeight = 80;
+
+const timestamps: ExtractFramesTimestampsInSecondsFn = async ({track}) => {
+ const aspectRatio = track.width / track.height;
+ const amountOfFramesFit = Math.ceil(canvasWidth / (canvasHeight * aspectRatio));
+ const timestampsInSeconds: number[] = [];
+ const segmentDuration = toSeconds - fromSeconds;
+
+ for (let i = 0; i < amountOfFramesFit; i++) {
+ timestampsInSeconds.push(fromSeconds + (segmentDuration / amountOfFramesFit) * (i + 0.5));
+ }
+
+ return timestampsInSeconds;
+};
+```
+
+Note that currently, you can not get the duration of the video in seconds before the extraction.
+For this you need currently to make another [`parseMedia()`](/docs/media-parser/parse-media) call beforehand.
+
+### `onFrame`
+
+A callback that will be called with the frame at the given timestamp.
+Each frame is a [`VideoFrame`](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame) object that can for example be drawn to a canvas.
+
+### `acknowledgeRemotionLicense?`
+
+Acknowledge the [Remotion License](/docs/license) to make the console message disappear.
+
+### `signal?`
+
+An optional [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to abort the extraction.
+
+### `logLevel?`
+
+_string_ <TsType type="LogLevel" source="@remotion/media-parser"/>
+
+One of `"error"`, `"warn"`, `"info"`, `"debug"`, `"trace"`.
+Default value: `"info"`, which logs only important information.
+
+## See also
+
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/webcodecs/src/extract-frames.ts)
+- [`@remotion/webcodecs`](/docs/webcodecs)
+- [`parseMedia()`](/docs/media-parser/parse-media)
+- [`parseMediaOnWebWorker()`](/docs/media-parser/parse-media-on-web-worker)
diff --git a/packages/docs/docs/webcodecs/extract-frames.mdx b/packages/docs/docs/webcodecs/extract-frames.mdx
index f388b1b367..9f89c28865 100644
--- a/packages/docs/docs/webcodecs/extract-frames.mdx
+++ b/packages/docs/docs/webcodecs/extract-frames.mdx
@@ -10,7 +10,7 @@ crumb: '@remotion/webcodecs'
_Part of the [`@remotion/webcodecs`](/docs/webcodecs) package._
-Extracts frames from a video at specific timestamps.
+Extracts frames from a video at specific timestamps using [`parseMedia()`](/docs/media-parser/parse-media).
```tsx twoslash title="Extracting frames"
import {extractFrames} from '@remotion/webcodecs';
@@ -49,16 +49,12 @@ const canvasHeight = 80;
const timestamps: ExtractFramesTimestampsInSecondsFn = async ({track}) => {
const aspectRatio = track.width / track.height;
- const amountOfFramesFit = Math.ceil(
- canvasWidth / (canvasHeight * aspectRatio),
- );
+ const amountOfFramesFit = Math.ceil(canvasWidth / (canvasHeight * aspectRatio));
const timestampsInSeconds: number[] = [];
const segmentDuration = toSeconds - fromSeconds;
for (let i = 0; i < amountOfFramesFit; i++) {
- timestampsInSeconds.push(
- fromSeconds + (segmentDuration / amountOfFramesFit) * (i + 0.5),
- );
+ timestampsInSeconds.push(fromSeconds + (segmentDuration / amountOfFramesFit) * (i + 0.5));
}
return timestampsInSeconds;
@@ -73,7 +69,6 @@ For this you need currently to make another [`parseMedia()`](/docs/media-parser/
A callback that will be called with the frame at the given timestamp.
Each frame is a [`VideoFrame`](https://developer.mozilla.org/en-US/docs/Web/API/VideoFrame) object that can for example be drawn to a canvas.
-
### `acknowledgeRemotionLicense?`
Acknowledge the [Remotion License](/docs/license) to make the console message disappear.
@@ -93,4 +88,4 @@ Default value: `"info"`, which logs only important information.
- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/webcodecs/src/extract-frames.ts)
- [`@remotion/webcodecs`](/docs/webcodecs)
-- [`parseMedia()`](/docs/media-parser/parse-media)
\ No newline at end of file
+- [`parseMedia()`](/docs/media-parser/parse-media)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 1236856287..9b1269d3bc 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -695,6 +695,7 @@ const sidebars: SidebarsConfig = {
'webcodecs/create-audio-decoder',
'webcodecs/create-video-decoder',
'webcodecs/extract-frames',
+ 'webcodecs/extract-frames-on-web-worker',
'webcodecs/rotate-and-resize-video-frame',
'webcodecs/web-fs-writer',
'webcodecs/buffer-writer',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 56a85af316..04d0998dea 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -5659,7 +5659,7 @@ export const articles = [
},
{
id: 'transparent-videos',
- title: 'Transparent videos',
+ title: 'Rendering transparent videos',
relativePath: 'docs/transparent-videos.mdx',
compId: 'articles-docs-transparent-videos',
crumb: 'Techniques',
@@ -6171,6 +6171,15 @@ export const articles = [
noAi: false,
slug: 'webcodecs/default-on-video-track-handler',
},
+ {
+ id: 'extract-frames-on-web-worker',
+ title: 'extractFramesOnWebWorker()',
+ relativePath: 'docs/webcodecs/extract-frames-on-web-worker.mdx',
+ compId: 'articles-docs-webcodecs-extract-frames-on-web-worker',
+ crumb: '@remotion/webcodecs',
+ noAi: false,
+ slug: 'webcodecs/extract-frames-on-web-worker',
+ },
{
id: 'extract-frames',
title: 'extractFrames()',
diff --git a/packages/docs/static/generated/articles-docs-webcodecs-extract-frames-on-web-worker.png b/packages/docs/static/generated/articles-docs-webcodecs-extract-frames-on-web-worker.png
new file mode 100644
index 0000000000..9a077a1502
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-webcodecs-extract-frames-on-web-worker.png differ
diff --git a/packages/media-parser/src/index.ts b/packages/media-parser/src/index.ts
index 8ed3beea6e..5b1b72cf17 100644
--- a/packages/media-parser/src/index.ts
+++ b/packages/media-parser/src/index.ts
@@ -28,6 +28,7 @@ import {Log} from './log';
import type {ParseMediaCallbacks} from './options';
import {fieldsNeedSamplesMap} from './state/need-samples-for-fields';
import {makeParserState} from './state/parser-state';
+export type {ParseMedia, ParseMediaCallbacks} from './options';
export {parseMedia} from './parse-media';
diff --git a/packages/webcodecs/bundle.ts b/packages/webcodecs/bundle.ts
index f0b97ed474..6284436a81 100644
--- a/packages/webcodecs/bundle.ts
+++ b/packages/webcodecs/bundle.ts
@@ -8,6 +8,7 @@ console.time('Generated.');
const output = await build({
entrypoints: [
'src/index.ts',
+ 'src/worker.ts',
'src/writers/buffer.ts',
'src/writers/web-fs.ts',
],
diff --git a/packages/webcodecs/package.json b/packages/webcodecs/package.json
index a7d39c8b45..05abd88580 100644
--- a/packages/webcodecs/package.json
+++ b/packages/webcodecs/package.json
@@ -63,6 +63,12 @@
"module": "./dist/esm/buffer.mjs",
"import": "./dist/esm/buffer.mjs"
},
+ "./worker": {
+ "types": "./dist/worker.d.ts",
+ "require": "./dist/worker.js",
+ "module": "./dist/esm/worker.mjs",
+ "import": "./dist/esm/worker.mjs"
+ },
"./package.json": "./package.json"
},
"typesVersions": {
@@ -70,6 +76,9 @@
"web-fs": [
"dist/writers/web-fs.d.ts"
],
+ "worker": [
+ "dist/worker.d.ts"
+ ],
"buffer": [
"dist/writers/buffer.d.ts"
]
diff --git a/packages/webcodecs/src/extract-frames-on-web-worker.ts b/packages/webcodecs/src/extract-frames-on-web-worker.ts
new file mode 100644
index 0000000000..4bd7b50ebb
--- /dev/null
+++ b/packages/webcodecs/src/extract-frames-on-web-worker.ts
@@ -0,0 +1,31 @@
+import {type MediaParserLogLevel} from '@remotion/media-parser';
+import {parseMediaOnWebWorker} from '@remotion/media-parser/worker';
+import {
+ internalExtractFrames,
+ type ExtractFramesTimestampsInSecondsFn,
+} from './internal-extract-frames';
+
+export type ExtractFramesOnWebWorkerProps = {
+ src: string;
+ timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
+ onFrame: (frame: VideoFrame) => void;
+ signal?: AbortSignal;
+ acknowledgeRemotionLicense?: boolean;
+ logLevel?: MediaParserLogLevel;
+};
+
+export type ExtractFramesOnWebWorker = (
+ options: ExtractFramesOnWebWorkerProps,
+) => Promise<void>;
+
+export const extractFramesOnWebWorker: ExtractFramesOnWebWorker = (
+ options: ExtractFramesOnWebWorkerProps,
+) => {
+ return internalExtractFrames({
+ ...options,
+ signal: options.signal ?? null,
+ acknowledgeRemotionLicense: options.acknowledgeRemotionLicense ?? false,
+ logLevel: options.logLevel ?? 'info',
+ parseMediaImplementation: parseMediaOnWebWorker,
+ });
+};
diff --git a/packages/webcodecs/src/extract-frames.ts b/packages/webcodecs/src/extract-frames.ts
index 6dec2fdeed..dc173b6ee6 100644
--- a/packages/webcodecs/src/extract-frames.ts
+++ b/packages/webcodecs/src/extract-frames.ts
@@ -1,237 +1,26 @@
-import type {
- MediaParserContainer,
- MediaParserLogLevel,
- MediaParserVideoSample,
- MediaParserVideoTrack,
-} from '@remotion/media-parser';
+import {parseMedia, type MediaParserLogLevel} from '@remotion/media-parser';
import {
- hasBeenAborted,
- MediaParserAbortError,
- mediaParserController,
- WEBCODECS_TIMESCALE,
-} from '@remotion/media-parser';
-import {parseMediaOnWebWorker} from '@remotion/media-parser/worker';
-import {createVideoDecoder} from './create-video-decoder';
-import {withResolvers} from './create/with-resolvers';
-import {Log} from './log';
+ internalExtractFrames,
+ type ExtractFramesTimestampsInSecondsFn,
+} from './internal-extract-frames';
-export type ExtractFramesTimestampsInSecondsFn = (options: {
- track: MediaParserVideoTrack;
- container: MediaParserContainer;
- durationInSeconds: number | null;
-}) => Promise<number[]> | number[];
-
-const internalExtractFrames = ({
- src,
- onFrame,
- signal,
- timestampsInSeconds,
- acknowledgeRemotionLicense,
- logLevel,
-}: {
- timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
- src: string;
- onFrame: (frame: VideoFrame) => void;
- signal: AbortSignal | null;
- acknowledgeRemotionLicense: boolean;
- logLevel: MediaParserLogLevel;
-}) => {
- const controller = mediaParserController();
-
- const expectedFrames: number[] = [];
-
- const resolvers = withResolvers<void>();
-
- const abortListener = () => {
- controller.abort();
- resolvers.reject(new MediaParserAbortError('Aborted by user'));
- };
-
- signal?.addEventListener('abort', abortListener, {once: true});
-
- let dur: number | null = null;
-
- let lastFrame: VideoFrame | undefined;
- let lastFrameEmitted: VideoFrame | undefined;
-
- parseMediaOnWebWorker({
- src: new URL(src, window.location.href),
- acknowledgeRemotionLicense,
- controller,
- logLevel,
- onDurationInSeconds(durationInSeconds) {
- dur = durationInSeconds;
- },
- onVideoTrack: async ({track, container}) => {
- const timestampTargetsUnsorted =
- typeof timestampsInSeconds === 'function'
- ? await timestampsInSeconds({
- track,
- container,
- durationInSeconds: dur,
- })
- : timestampsInSeconds;
-
- const timestampTargets = timestampTargetsUnsorted.sort((a, b) => a - b);
-
- if (timestampTargets.length === 0) {
- throw new Error(
- 'expected at least one timestamp to extract but found zero',
- );
- }
-
- controller.seek(timestampTargets[0]);
-
- const decoder = createVideoDecoder({
- onFrame: (frame) => {
- Log.trace(logLevel, 'Received frame with timestamp', frame.timestamp);
- if (expectedFrames.length === 0) {
- frame.close();
- return;
- }
-
- if (frame.timestamp < expectedFrames[0] - 1) {
- if (lastFrame) {
- lastFrame.close();
- }
-
- lastFrame = frame;
- return;
- }
-
- // A WebM might have a timestamp of 67000 but we request 66666
- // See a test with this problem in it-tests/rendering/frame-accuracy.test.ts
- // Solution: We allow a 10.000ms - 3.333ms = 6.667ms difference between the requested timestamp and the actual timestamp
- if (expectedFrames[0] + 6667 < frame.timestamp && lastFrame) {
- onFrame(lastFrame);
- lastFrameEmitted = lastFrame;
- expectedFrames.shift();
- lastFrame = frame;
- return;
- }
-
- expectedFrames.shift();
- onFrame(frame);
- lastFrameEmitted = frame;
- lastFrame = frame;
- },
- onError: (e) => {
- controller.abort();
- try {
- decoder.close();
- } catch {}
-
- resolvers.reject(e);
- },
- track,
- });
-
- const queued: MediaParserVideoSample[] = [];
-
- const doProcess = async () => {
- expectedFrames.push(
- (timestampTargets.shift() as number) * WEBCODECS_TIMESCALE,
- );
-
- while (queued.length > 0) {
- const sam = queued.shift();
- if (!sam) {
- throw new Error('Sample is undefined');
- }
-
- await decoder.waitForQueueToBeLessThan(10);
- Log.trace(logLevel, 'Decoding sample', sam.timestamp);
- await decoder.decode(sam);
- }
- };
-
- return async (sample) => {
- const nextTimestampWeWant = timestampTargets[0];
- Log.trace(
- logLevel,
- 'Received sample with dts',
- sample.decodingTimestamp,
- 'and cts',
- sample.timestamp,
- );
-
- if (sample.type === 'key') {
- await decoder.flush();
- queued.length = 0;
- }
-
- queued.push(sample);
-
- if (
- sample.decodingTimestamp >=
- timestampTargets[timestampTargets.length - 1] * WEBCODECS_TIMESCALE
- ) {
- await doProcess();
-
- await decoder.flush();
- controller.abort();
- return;
- }
-
- if (nextTimestampWeWant === undefined) {
- throw new Error('this should not happen');
- }
-
- if (
- sample.decodingTimestamp >=
- nextTimestampWeWant * WEBCODECS_TIMESCALE
- ) {
- await doProcess();
-
- if (timestampTargets.length === 0) {
- await decoder.flush();
- controller.abort();
- }
- }
-
- return async () => {
- await doProcess();
- await decoder.flush();
- if (lastFrame && lastFrameEmitted !== lastFrame) {
- lastFrame.close();
- }
- };
- };
- },
- })
- .then(() => {
- resolvers.resolve();
- })
- .catch((e) => {
- if (!hasBeenAborted(e)) {
- resolvers.reject(e);
- } else {
- resolvers.resolve();
- }
- })
- .finally(() => {
- if (lastFrame && lastFrameEmitted !== lastFrame) {
- lastFrame.close();
- }
-
- signal?.removeEventListener('abort', abortListener);
- });
-
- return resolvers.promise;
-};
-
-export const extractFrames = (options: {
+export type ExtractFramesProps = {
src: string;
timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
onFrame: (frame: VideoFrame) => void;
signal?: AbortSignal;
acknowledgeRemotionLicense?: boolean;
logLevel?: MediaParserLogLevel;
-}) => {
+};
+
+export type ExtractFrames = (options: ExtractFramesProps) => Promise<void>;
+
+export const extractFrames: ExtractFrames = (options: ExtractFramesProps) => {
return internalExtractFrames({
...options,
signal: options.signal ?? null,
acknowledgeRemotionLicense: options.acknowledgeRemotionLicense ?? false,
logLevel: options.logLevel ?? 'info',
+ parseMediaImplementation: parseMedia,
});
};
diff --git a/packages/webcodecs/src/index.ts b/packages/webcodecs/src/index.ts
index 5462b42ffd..ac116808dc 100644
--- a/packages/webcodecs/src/index.ts
+++ b/packages/webcodecs/src/index.ts
@@ -26,8 +26,11 @@ export {createVideoDecoder} from './create-video-decoder';
export type {WebCodecsVideoDecoder} from './create-video-decoder';
export {defaultOnAudioTrackHandler} from './default-on-audio-track-handler';
export {defaultOnVideoTrackHandler} from './default-on-video-track-handler';
-export {extractFrames} from './extract-frames';
-export type {ExtractFramesTimestampsInSecondsFn} from './extract-frames';
+export {
+ extractFrames,
+ ExtractFrames,
+ ExtractFramesProps,
+} from './extract-frames';
export {getAvailableAudioCodecs} from './get-available-audio-codecs';
export type {ConvertMediaAudioCodec} from './get-available-audio-codecs';
export {getAvailableContainers} from './get-available-containers';
@@ -40,6 +43,7 @@ export {
getPartialAudioData,
GetPartialAudioDataProps,
} from './get-partial-audio-data';
+export type {ExtractFramesTimestampsInSecondsFn} from './internal-extract-frames';
export type {
AudioOperation,
ConvertMediaOnAudioTrackHandler,
diff --git a/packages/webcodecs/src/internal-extract-frames.ts b/packages/webcodecs/src/internal-extract-frames.ts
new file mode 100644
index 0000000000..af5d5cd7aa
--- /dev/null
+++ b/packages/webcodecs/src/internal-extract-frames.ts
@@ -0,0 +1,224 @@
+import type {
+ MediaParserContainer,
+ MediaParserLogLevel,
+ MediaParserVideoSample,
+ MediaParserVideoTrack,
+ ParseMedia,
+} from '@remotion/media-parser';
+import {
+ MediaParserAbortError,
+ WEBCODECS_TIMESCALE,
+ hasBeenAborted,
+ mediaParserController,
+} from '@remotion/media-parser';
+import type {ParseMediaOnWorker} from '@remotion/media-parser/worker';
+import {createVideoDecoder} from './create-video-decoder';
+import {withResolvers} from './create/with-resolvers';
+import {Log} from './log';
+
+export type ExtractFramesTimestampsInSecondsFn = (options: {
+ track: MediaParserVideoTrack;
+ container: MediaParserContainer;
+ durationInSeconds: number | null;
+}) => Promise<number[]> | number[];
+
+export const internalExtractFrames = ({
+ src,
+ onFrame,
+ signal,
+ timestampsInSeconds,
+ acknowledgeRemotionLicense,
+ logLevel,
+ parseMediaImplementation,
+}: {
+ timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
+ src: string;
+ onFrame: (frame: VideoFrame) => void;
+ signal: AbortSignal | null;
+ acknowledgeRemotionLicense: boolean;
+ logLevel: MediaParserLogLevel;
+ parseMediaImplementation: ParseMediaOnWorker | ParseMedia;
+}) => {
+ const controller = mediaParserController();
+
+ const expectedFrames: number[] = [];
+
+ const resolvers = withResolvers<void>();
+
+ const abortListener = () => {
+ controller.abort();
+ resolvers.reject(new MediaParserAbortError('Aborted by user'));
+ };
+
+ signal?.addEventListener('abort', abortListener, {once: true});
+
+ let dur: number | null = null;
+
+ let lastFrame: VideoFrame | undefined;
+ let lastFrameEmitted: VideoFrame | undefined;
+
+ parseMediaImplementation({
+ src: new URL(src, window.location.href),
+ acknowledgeRemotionLicense,
+ controller,
+ logLevel,
+ onDurationInSeconds(durationInSeconds) {
+ dur = durationInSeconds;
+ },
+ onVideoTrack: async ({track, container}) => {
+ const timestampTargetsUnsorted =
+ typeof timestampsInSeconds === 'function'
+ ? await timestampsInSeconds({
+ track,
+ container,
+ durationInSeconds: dur,
+ })
+ : timestampsInSeconds;
+
+ const timestampTargets = timestampTargetsUnsorted.sort((a, b) => a - b);
+
+ if (timestampTargets.length === 0) {
+ throw new Error(
+ 'expected at least one timestamp to extract but found zero',
+ );
+ }
+
+ controller.seek(timestampTargets[0]);
+
+ const decoder = createVideoDecoder({
+ onFrame: (frame) => {
+ Log.trace(logLevel, 'Received frame with timestamp', frame.timestamp);
+ if (expectedFrames.length === 0) {
+ frame.close();
+ return;
+ }
+
+ if (frame.timestamp < expectedFrames[0] - 1) {
+ if (lastFrame) {
+ lastFrame.close();
+ }
+
+ lastFrame = frame;
+ return;
+ }
+
+ // A WebM might have a timestamp of 67000 but we request 66666
+ // See a test with this problem in it-tests/rendering/frame-accuracy.test.ts
+ // Solution: We allow a 10.000ms - 3.333ms = 6.667ms difference between the requested timestamp and the actual timestamp
+ if (expectedFrames[0] + 6667 < frame.timestamp && lastFrame) {
+ onFrame(lastFrame);
+ lastFrameEmitted = lastFrame;
+ expectedFrames.shift();
+ lastFrame = frame;
+ return;
+ }
+
+ expectedFrames.shift();
+ onFrame(frame);
+ lastFrameEmitted = frame;
+ lastFrame = frame;
+ },
+ onError: (e) => {
+ controller.abort();
+ try {
+ decoder.close();
+ } catch {}
+
+ resolvers.reject(e);
+ },
+ track,
+ });
+
+ const queued: MediaParserVideoSample[] = [];
+
+ const doProcess = async () => {
+ expectedFrames.push(
+ (timestampTargets.shift() as number) * WEBCODECS_TIMESCALE,
+ );
+
+ while (queued.length > 0) {
+ const sam = queued.shift();
+ if (!sam) {
+ throw new Error('Sample is undefined');
+ }
+
+ await decoder.waitForQueueToBeLessThan(10);
+ Log.trace(logLevel, 'Decoding sample', sam.timestamp);
+ await decoder.decode(sam);
+ }
+ };
+
+ return async (sample) => {
+ const nextTimestampWeWant = timestampTargets[0];
+ Log.trace(
+ logLevel,
+ 'Received sample with dts',
+ sample.decodingTimestamp,
+ 'and cts',
+ sample.timestamp,
+ );
+
+ if (sample.type === 'key') {
+ await decoder.flush();
+ queued.length = 0;
+ }
+
+ queued.push(sample);
+
+ if (
+ sample.decodingTimestamp >=
+ timestampTargets[timestampTargets.length - 1] * WEBCODECS_TIMESCALE
+ ) {
+ await doProcess();
+
+ await decoder.flush();
+ controller.abort();
+ return;
+ }
+
+ if (nextTimestampWeWant === undefined) {
+ throw new Error('this should not happen');
+ }
+
+ if (
+ sample.decodingTimestamp >=
+ nextTimestampWeWant * WEBCODECS_TIMESCALE
+ ) {
+ await doProcess();
+
+ if (timestampTargets.length === 0) {
+ await decoder.flush();
+ controller.abort();
+ }
+ }
+
+ return async () => {
+ await doProcess();
+ await decoder.flush();
+ if (lastFrame && lastFrameEmitted !== lastFrame) {
+ lastFrame.close();
+ }
+ };
+ };
+ },
+ })
+ .then(() => {
+ resolvers.resolve();
+ })
+ .catch((e) => {
+ if (!hasBeenAborted(e)) {
+ resolvers.reject(e);
+ } else {
+ resolvers.resolve();
+ }
+ })
+ .finally(() => {
+ if (lastFrame && lastFrameEmitted !== lastFrame) {
+ lastFrame.close();
+ }
+
+ signal?.removeEventListener('abort', abortListener);
+ });
+
+ return resolvers.promise;
+};
diff --git a/packages/webcodecs/src/worker.ts b/packages/webcodecs/src/worker.ts
new file mode 100644
index 0000000000..33c661baec
--- /dev/null
+++ b/packages/webcodecs/src/worker.ts
@@ -0,0 +1,5 @@
+export {
+ ExtractFramesOnWebWorker,
+ ExtractFramesOnWebWorkerProps,
+ extractFramesOnWebWorker,
+} from './extract-frames-on-web-worker';