🎥 Make videos programmatically with React
`@remotion/webcodecs`: New extractFrames() API
Jonny Burger8d8cc3276968
diff --git a/packages/docs/docs/webcodecs/TableOfContents.tsx b/packages/docs/docs/webcodecs/TableOfContents.tsxindex 0345b6bfc6..4a8db61067 100644--- a/packages/docs/docs/webcodecs/TableOfContents.tsx+++ b/packages/docs/docs/webcodecs/TableOfContents.tsx@@ -122,6 +122,10 @@ export const TableOfContents: React.FC = () => {Create a <code>VideoDecoder</code> object.</div></TOCItem>+ <TOCItem link="/docs/webcodecs/extract-frames">+ <strong>{'extractFrames()'}</strong>+ <div>Extract frames from a video at specific timestamps.</div>+ </TOCItem></Grid></div>);diff --git a/packages/docs/docs/webcodecs/extract-frames.mdx b/packages/docs/docs/webcodecs/extract-frames.mdxnew file mode 100644index 0000000000..21e082efca--- /dev/null+++ b/packages/docs/docs/webcodecs/extract-frames.mdx@@ -0,0 +1,83 @@+---+id: extract-frames+title: extractFrames()+slug: /webcodecs/extract-frames+crumb: '@remotion/webcodecs'+---++# extractFrames()<AvailableFrom v="4.0.311"/>++_Part of the [`@remotion/webcodecs`](/docs/webcodecs) package._++Extracts frames from a video at specific timestamps.++```tsx twoslash title="Extracting frames"+import {extractFrames} from '@remotion/webcodecs';++await extractFrames({+ 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.++### `signal?`++An optional [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to abort the extraction.++## 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)\ No newline at end of filediff --git a/packages/docs/docs/webcodecs/index.mdx b/packages/docs/docs/webcodecs/index.mdxindex fd87adeb9a..ffbb5ad99e 100644--- a/packages/docs/docs/webcodecs/index.mdx+++ b/packages/docs/docs/webcodecs/index.mdx@@ -16,12 +16,13 @@ It leverages [`@remotion/media-parser`](/docs/media-parser) to parse the video aimport {LicenseDisclaimer} from './LicenseDisclaimer';import {UnstableDisclaimer} from './UnstableDisclaimer';-## What can you to with this package?+## What can you do with this package?In browsers that implement WebCodecs, you can use this package to:- [Convert videos from one format to another](/docs/webcodecs/convert-a-video) (From .mp4, .webm, .mov, .mkv, .m3u8, .ts, .avi, .mp3, .flac, .wav, .m4a, .aac to .mp4, .webm, .wav)- [Rotate videos](/docs/webcodecs/rotate-a-video)+- [Efficiently extract frames from a video](/docs/webcodecs/extract-frames)- Extract audio from a video- Manipulate the pixels of a video- [Fix videos that were recorded with `MediaRecorder`](/docs/webcodecs/fix-mediarecorder-video)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex c4c3a13047..0a82cafe54 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -685,6 +685,7 @@ module.exports = {'webcodecs/convert-audiodata','webcodecs/create-audio-decoder','webcodecs/create-video-decoder',+ 'webcodecs/extract-frames',],},{diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex d6c2e29b34..e32c71706a 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2971,7 +2971,7 @@ export const articles = [},{id: 'webcodecs',- title: 'Decoding a video with WebCodecs and @remotion/media-parser',+ title: 'Processing video with WebCodecs and @remotion/media-parser',relativePath: 'docs/media-parser/webcodecs.mdx',compId: 'articles-docs-media-parser-webcodecs',crumb: '@remotion/media-parser',@@ -6045,6 +6045,15 @@ export const articles = [noAi: false,slug: 'webcodecs/default-on-video-track-handler',},+ {+ id: 'extract-frames',+ title: 'extractFrames()',+ relativePath: 'docs/webcodecs/extract-frames.mdx',+ compId: 'articles-docs-webcodecs-extract-frames',+ crumb: '@remotion/webcodecs',+ noAi: false,+ slug: 'webcodecs/extract-frames',+ },{id: 'fix-mediarecorder-video',title: 'Fixing a MediaRecorder video',diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsxindex b505ddb3be..86b25ddd0b 100644--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx@@ -224,7 +224,7 @@ export const TimelineVideoInfo: React.FC<{const controller = new AbortController();extractFrames({- timestamps: ({track}) => {+ timestampsInSeconds: ({track}) => {const aspectRatio = track.width / track.height;const framesFitInWidth = Math.ceil(visualizationWidth / (HEIGHT * aspectRatio),diff --git a/packages/webcodecs/src/extract-frames.ts b/packages/webcodecs/src/extract-frames.tsindex 232a94b09b..16b3bd9fcf 100644--- a/packages/webcodecs/src/extract-frames.ts+++ b/packages/webcodecs/src/extract-frames.ts@@ -12,21 +12,21 @@ import {parseMediaOnWebWorker} from '@remotion/media-parser/worker';import {createVideoDecoder} from './create-video-decoder';import {withResolvers} from './create/with-resolvers';-export type ExtractFrameGetTimestamps = (options: {+export type ExtractFramesTimestampsInSecondsFn = (options: {track: MediaParserVideoTrack;durationInSeconds: number | null;}) => Promise<number[]> | number[];-export const extractFrames = ({+const internalExtractFrames = ({src,onFrame,signal,- timestamps,+ timestampsInSeconds,}: {- timestamps: ExtractFrameGetTimestamps;+ timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;src: string;onFrame: (frame: VideoFrame) => void;- signal: AbortSignal;+ signal: AbortSignal | null;}) => {const controller = mediaParserController();@@ -39,7 +39,7 @@ export const extractFrames = ({resolvers.reject(new MediaParserAbortError('Aborted by user'));};- signal.addEventListener('abort', abortListener, {once: true});+ signal?.addEventListener('abort', abortListener, {once: true});let dur: number | null = null;@@ -51,12 +51,15 @@ export const extractFrames = ({dur = durationInSeconds;},onVideoTrack: async ({track}) => {- const timestampTargets_ = await timestamps({- track,- durationInSeconds: dur,- });+ const timestampTargetsUnsorted =+ typeof timestampsInSeconds === 'function'+ ? await timestampsInSeconds({+ track,+ durationInSeconds: dur,+ })+ : timestampsInSeconds;- const timestampTargets = timestampTargets_.sort((a, b) => a - b);+ const timestampTargets = timestampTargetsUnsorted.sort((a, b) => a - b);controller.seek(timestampTargets[0]);@@ -134,8 +137,17 @@ export const extractFrames = ({}}).finally(() => {- signal.removeEventListener('abort', abortListener);+ signal?.removeEventListener('abort', abortListener);});return resolvers.promise;};++export const extractFrames = (options: {+ src: string;+ timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;+ onFrame: (frame: VideoFrame) => void;+ signal?: AbortSignal;+}) => {+ return internalExtractFrames({...options, signal: options.signal ?? null});+};diff --git a/packages/webcodecs/src/index.ts b/packages/webcodecs/src/index.tsindex a386646f56..479912d595 100644--- a/packages/webcodecs/src/index.ts+++ b/packages/webcodecs/src/index.ts@@ -27,6 +27,7 @@ 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 {getAvailableAudioCodecs} from './get-available-audio-codecs';export type {ConvertMediaAudioCodec} from './get-available-audio-codecs';export {getAvailableContainers} from './get-available-containers';