Skip to content

🎥 Make videos programmatically with React

add docs and fix import

Igor Samokhovets377c0d311fe6
diff --git a/packages/docs/docs/mediabunny/extract-frames.mdx b/packages/docs/docs/mediabunny/extract-frames.mdx
new file mode 100644
index 0000000000..35bb7cc1ff
--- /dev/null
+++ b/packages/docs/docs/mediabunny/extract-frames.mdx
@@ -0,0 +1,201 @@
+---
+image: /generated/articles-docs-mediabunny-extract-frames.png
+title: Extracting video frames
+crumb: 'Mediabunny'
+sidebar_label: Extracting video frames
+---
+
+Extracting frames from a video file is useful for creating thumbnails, filmstrips, or analyzing video content.
+
+This guide shows how to extract frames at specific timestamps using mediabunny.
+
+## Use cases
+
+- **Video thumbnails**: Generate preview images for video players or galleries
+- **Filmstrip previews**: Show a timeline preview with frames from the video (like in the Remotion Studio)
+- **Frame analysis**: Extract frames for image processing or computer vision tasks
+- **Sprite sheets**: Create a sprite sheet of video frames for efficient seeking
+
+## Implementation
+
+Here's a complete implementation using mediabunny's `VideoSampleSink`:
+
+```ts twoslash title="extractFrames() API snippet"
+import {ALL_FORMATS, Input, InputDisposedError, UrlSource, VideoSampleSink} from 'mediabunny';
+
+export type ExtractFramesTimestampsInSecondsFn = (options: {track: {width: number; height: number}; container: string; durationInSeconds: number | null}) => Promise<number[]> | number[];
+
+export type ExtractFramesProps = {
+ src: string;
+ timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
+ onFrame: (frame: VideoFrame) => void;
+ signal?: AbortSignal;
+};
+
+export async function extractFrames({src, timestampsInSeconds, onFrame, signal}: ExtractFramesProps): Promise<void> {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
+
+ if (signal) {
+ signal.addEventListener(
+ 'abort',
+ () => {
+ input.dispose();
+ },
+ {once: true},
+ );
+ }
+
+ try {
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+
+ const [durationInSeconds, format] = await Promise.all([input.computeDuration(), input.getFormat()]);
+
+ const timestamps =
+ typeof timestampsInSeconds === 'function'
+ ? await timestampsInSeconds({
+ track: {
+ width: videoTrack.codedWidth,
+ height: videoTrack.codedHeight,
+ },
+ container: format.name,
+ durationInSeconds,
+ })
+ : timestampsInSeconds;
+
+ if (timestamps.length === 0) {
+ return;
+ }
+
+ const sink = new VideoSampleSink(videoTrack);
+
+ for await (const videoSample of sink.samplesAtTimestamps(timestamps)) {
+ if (signal?.aborted) {
+ break;
+ }
+
+ if (!videoSample) {
+ continue;
+ }
+
+ const videoFrame = videoSample.toVideoFrame();
+
+ onFrame(videoFrame);
+ }
+ } catch (error) {
+ if (error instanceof InputDisposedError) {
+ return;
+ }
+
+ throw error;
+ } finally {
+ input.dispose();
+ }
+}
+```
+
+## Usage
+
+### Basic example: Extract frames at specific times
+
+```ts
+await extractFrames({
+ src: 'https://example.com/video.mp4',
+ timestampsInSeconds: [0, 1, 2, 3, 4],
+ onFrame: (frame) => {
+ // Draw frame to canvas
+ const canvas = document.createElement('canvas');
+ canvas.width = frame.displayWidth;
+ canvas.height = frame.displayHeight;
+ const ctx = canvas.getContext('2d');
+ ctx.drawImage(frame, 0, 0);
+
+ // Don't forget to close the frame when done
+ frame.close();
+ },
+});
+```
+
+### Advanced: Create a filmstrip
+
+Extract as many frames as fit in a canvas based on the video's aspect ratio:
+
+```ts
+const canvasWidth = 500;
+const canvasHeight = 80;
+const fromSeconds = 0;
+const toSeconds = 10;
+
+await extractFrames({
+ src: 'https://example.com/video.mp4',
+ timestampsInSeconds: async ({track, durationInSeconds}) => {
+ const aspectRatio = track.width / track.height;
+ const amountOfFramesFit = Math.ceil(canvasWidth / (canvasHeight * aspectRatio));
+ const segmentDuration = toSeconds - fromSeconds;
+ const timestamps: number[] = [];
+
+ for (let i = 0; i < amountOfFramesFit; i++) {
+ timestamps.push(fromSeconds + (segmentDuration / amountOfFramesFit) * (i + 0.5));
+ }
+
+ return timestamps;
+ },
+ onFrame: (frame) => {
+ // Process each frame
+ console.log(`Frame at ${frame.timestamp / 1_000_000}s`);
+ frame.close();
+ },
+});
+```
+
+## Important notes
+
+### Memory management
+
+Always close `VideoFrame` objects when you're done with them to prevent memory leaks:
+
+```ts
+onFrame: (frame) => {
+ // Use the frame
+ ctx.drawImage(frame, 0, 0);
+
+ // Clean up
+ frame.close();
+};
+```
+
+### Abort handling
+
+Use an `AbortSignal` to cancel frame extraction:
+
+```ts
+const controller = new AbortController();
+
+// Cancel after 5 seconds
+setTimeout(() => controller.abort(), 5000);
+
+await extractFrames({
+ src: 'https://example.com/video.mp4',
+ timestampsInSeconds: [0, 1, 2, 3, 4],
+ onFrame: (frame) => {
+ // Process frame
+ frame.close();
+ },
+ signal: controller.signal,
+});
+```
+
+### VideoFrame timestamps
+
+`VideoFrame.timestamp` is in **microseconds**, while mediabunny's `VideoSample.timestamp` is in **seconds**. The conversion is handled automatically by `.toVideoFrame()`.
+
+## See also
+
+- [Mediabunny Documentation](https://mediabunny.dev)
+- [VideoSampleSink API](https://mediabunny.dev/api/class/VideoSampleSink)
+- [Supported formats](/docs/mediabunny/formats)
diff --git a/packages/docs/docs/webcodecs/extract-frames.mdx b/packages/docs/docs/webcodecs/extract-frames.mdx
index 1c69c5cf9d..efb7ee5373 100644
--- a/packages/docs/docs/webcodecs/extract-frames.mdx
+++ b/packages/docs/docs/webcodecs/extract-frames.mdx
@@ -7,7 +7,8 @@ crumb: '@remotion/webcodecs'
---
:::warning
-[We are phasing out Remotion WebCodecs and are moving to Mediabunny](/blog/mediabunny)!
+[We are phasing out Remotion WebCodecs and are moving to Mediabunny](/blog/mediabunny)!
+**We recommend using [mediabunny for extracting frames](/docs/mediabunny/extract-frames) instead.**
:::
# extractFrames()<AvailableFrom v="4.0.311"/>
@@ -16,6 +17,8 @@ _Part of the [`@remotion/webcodecs`](/docs/webcodecs) package._
Extracts frames from a video at specific timestamps using [`parseMedia()`](/docs/media-parser/parse-media).
+Since Remotion is migrating to [mediabunny](https://mediabunny.dev), we recommend using the [mediabunny-based frame extraction implementation](/docs/mediabunny/extract-frames) for new projects.
+
```tsx twoslash title="Extracting frames"
import {extractFrames} from '@remotion/webcodecs';
@@ -90,6 +93,7 @@ Default value: `"info"`, which logs only important information.
## See also
+- **[Extracting frames with mediabunny](/docs/mediabunny/extract-frames)** (recommended)
- [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)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index a9e2e7167c..1258ee81c4 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -1227,6 +1227,7 @@ const sidebars: SidebarsConfig = {
'mediabunny/index',
'mediabunny/new-video',
'mediabunny/metadata',
+ 'mediabunny/extract-frames',
'mediabunny/formats',
'mediabunny/version',
],
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index cce3a94913..3731760eea 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -3338,6 +3338,15 @@ export const articles = [
noAi: false,
slug: 'media/video',
},
+ {
+ id: 'mediabunny/extract-frames',
+ title: 'Extracting video frames',
+ relativePath: 'docs/mediabunny/extract-frames.mdx',
+ compId: 'articles-docs-mediabunny-extract-frames',
+ crumb: 'Mediabunny',
+ noAi: false,
+ slug: 'mediabunny/extract-frames',
+ },
{
id: 'mediabunny/formats',
title: 'Supported formats and codecs by Mediabunny',
diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
index 3c79cfcaa6..209c16dc35 100644
--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx
@@ -2,7 +2,7 @@ import {hasBeenAborted, WEBCODECS_TIMESCALE} from '@remotion/media-parser';
import {rotateAndResizeVideoFrame} from '@remotion/webcodecs';
import React, {useEffect, useRef, useState} from 'react';
import {useVideoConfig} from 'remotion';
-import {extractFrames} from '../../helpers/extract-frames-mediabunny';
+import {extractFrames} from '../../helpers/extract-frames';
import type {FrameDatabaseKey} from '../../helpers/frame-database';
import {
aspectRatioCache,