Skip to content

🎥 Make videos programmatically with React

update docs

JonnyBurgerce2330dd3019
diff --git a/packages/docs/docs/mediabunny/extract-frames.mdx b/packages/docs/docs/mediabunny/extract-frames.mdx
index 0c552b7391..ca61313c32 100644
--- a/packages/docs/docs/mediabunny/extract-frames.mdx
+++ b/packages/docs/docs/mediabunny/extract-frames.mdx
@@ -28,65 +28,51 @@ export type ExtractFramesProps = {
};
export async function extractFrames({src, timestampsInSeconds, onVideoSample, signal}: ExtractFramesProps): Promise<void> {
- const input = new Input({
+ using input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src),
});
- const dispose = () => {
- input.dispose();
- };
-
- if (signal) {
- signal.addEventListener('abort', dispose, {once: true});
+ const [durationInSeconds, format, videoTrack] = await Promise.all([input.computeDuration(), input.getFormat(), input.getPrimaryVideoTrack()]);
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+ if (signal?.aborted) {
+ throw new Error('Aborted');
}
- try {
- const [durationInSeconds, format, videoTrack] = await Promise.all([input.computeDuration(), input.getFormat(), input.getPrimaryVideoTrack()]);
- if (!videoTrack) {
- throw new Error('No video track found in the input');
- }
-
- const timestamps =
- typeof timestampsInSeconds === 'function'
- ? await timestampsInSeconds({
- track: {
- width: videoTrack.displayWidth,
- height: videoTrack.displayHeight,
- },
- container: format.name,
- durationInSeconds,
- })
- : timestampsInSeconds;
-
- if (timestamps.length === 0) {
- return;
- }
-
- const sink = new VideoSampleSink(videoTrack);
+ const timestamps =
+ typeof timestampsInSeconds === 'function'
+ ? await timestampsInSeconds({
+ track: {
+ width: videoTrack.displayWidth,
+ height: videoTrack.displayHeight,
+ },
+ container: format.name,
+ durationInSeconds,
+ })
+ : timestampsInSeconds;
+
+ if (timestamps.length === 0) {
+ return;
+ }
- for await (const videoSample of sink.samplesAtTimestamps(timestamps)) {
- if (signal?.aborted) {
- break;
- }
+ if (signal?.aborted) {
+ throw new Error('Aborted');
+ }
- if (!videoSample) {
- continue;
- }
+ const sink = new VideoSampleSink(videoTrack);
- onVideoSample(videoSample);
- }
- } catch (error) {
- if (error instanceof InputDisposedError) {
- return;
+ for await (using videoSample of sink.samplesAtTimestamps(timestamps)) {
+ if (signal?.aborted) {
+ break;
}
- throw error;
- } finally {
- dispose();
- if (signal) {
- signal.removeEventListener('abort', dispose);
+ if (!videoSample) {
+ continue;
}
+
+ onVideoSample(videoSample);
}
}
```
@@ -100,18 +86,12 @@ await extractFrames({
src: 'https://remotion.media/video.mp4',
timestampsInSeconds: [0, 1, 2, 3, 4],
onVideoSample: (sample) => {
- // Convert sample to VideoFrame
- const frame = sample.toVideoFrame();
-
// Draw frame to canvas
const canvas = document.createElement('canvas');
- canvas.width = frame.displayWidth;
- canvas.height = frame.displayHeight;
+ canvas.width = sample.displayWidth;
+ canvas.height = sample.displayHeight;
const ctx = canvas.getContext('2d');
- ctx.drawImage(frame, 0, 0);
-
- // Don't forget to close the frame when done
- frame.close();
+ sample.draw(ctx!, 0, 0);
},
});
```
@@ -141,62 +121,98 @@ await extractFrames({
return timestamps;
},
onVideoSample: (sample) => {
- // Convert to VideoFrame if needed
- const frame = sample.toVideoFrame();
-
- // Process the frame
+ // Process the sample
console.log(`Frame at ${sample.timestamp}s`);
- // Clean up
- frame.close();
+ // Draw to canvas or process as needed
+ const canvas = document.createElement('canvas');
+ canvas.width = sample.displayWidth;
+ canvas.height = sample.displayHeight;
+ const ctx = canvas.getContext('2d');
+ sample.draw(ctx!, 0, 0);
},
});
```
-## Important notes
+## Memory management
-### Memory management
+The the example above, the [`using`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using) keyword is used to automatically close the `VideoSample` and `ÃŒnput` objects when they goes out of scope. Make sure to keep no references to them to ensure proper cleanup.
-The `onVideoSample` callback receives a `VideoSample` object. You need to convert it to a `VideoFrame` using `.toVideoFrame()`, and always close the `VideoFrame` when you're done with it to prevent memory leaks:
+## Abort frame extraction
+
+Pass an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to cancel frame extraction:
```ts
-onVideoSample: (sample) => {
- const frame = sample.toVideoFrame();
+const controller = new AbortController();
- // Use the frame
- ctx.drawImage(frame, 0, 0);
+// Cancel after 5 seconds
+setTimeout(() => controller.abort(), 5000);
- // Clean up
- frame.close();
-};
+try {
+ await extractFrames({
+ src: 'https://example.com/video.mp4',
+ timestampsInSeconds: [0, 1, 2, 3, 4],
+ onVideoSample: (sample) => {
+ using frame = sample;
+ const canvas = document.createElement('canvas');
+ canvas.width = frame.displayWidth;
+ canvas.height = frame.displayHeight;
+ const ctx = canvas.getContext('2d');
+ frame.draw(ctx!, 0, 0);
+ },
+ signal: controller.signal,
+ });
+
+ console.log('Frame extraction complete!');
+} catch (error) {
+ console.error('Frame extraction was aborted or failed:', error);
+}
```
-### Abort handling
+## Setting a timeout
-Use an `AbortSignal` to cancel frame extraction:
+Here is how you can set a maximum duration for extracting frames:
-```ts
+```ts title="Fail if not able to extract within 10 seconds"
const controller = new AbortController();
-// Cancel after 5 seconds
-setTimeout(() => controller.abort(), 5000);
+const timeoutPromise = new Promise<never>((_, reject) => {
+ const timeoutId = setTimeout(() => {
+ controller.abort();
+ reject(new Error('Frame extraction timed out after 10 seconds'));
+ }, 10000);
-await extractFrames({
- src: 'https://example.com/video.mp4',
- timestampsInSeconds: [0, 1, 2, 3, 4],
- onVideoSample: (sample) => {
- const frame = sample.toVideoFrame();
- // Process frame
- frame.close();
- },
- signal: controller.signal,
+ controller.signal.addEventListener('abort', () => clearTimeout(timeoutId), {once: true});
});
+
+try {
+ await Promise.race([
+ extractFrames({
+ src: 'https://example.com/video.mp4',
+ timestampsInSeconds: [0, 1, 2, 3, 4],
+ onVideoSample: (sample) => {
+ using frame = sample;
+ const canvas = document.createElement('canvas');
+ canvas.width = frame.displayWidth;
+ canvas.height = frame.displayHeight;
+ const ctx = canvas.getContext('2d');
+ frame.draw(ctx!, 0, 0);
+ },
+ signal: controller.signal,
+ }),
+ timeoutPromise,
+ ]);
+
+ console.log('Frame extraction complete!');
+} catch (error) {
+ console.error('Frame extraction was aborted or failed:', error);
+}
```
## See also
-- [Extracting thumbnail](/docs/mediabunny/extract-thumbnail) - Extract a single frame from a video
+- [Extracting a single thumbnail](/docs/mediabunny/extract-thumbnail) - Extract a single frame from a video
- [Mediabunny Documentation](https://mediabunny.dev)
- [Packets & samples in Mediabunny](https://mediabunny.dev/guide/packets-and-samples)
-- [VideoSampleSink API](https://mediabunny.dev/api/class/VideoSampleSink)
+- [`VideoSampleSink` API](https://mediabunny.dev/api/class/VideoSampleSink)
- [Supported formats](/docs/mediabunny/formats)
diff --git a/packages/docs/docs/mediabunny/extract-thumbnail.mdx b/packages/docs/docs/mediabunny/extract-thumbnail.mdx
index 3b4c0f83a7..c6f3677b1c 100644
--- a/packages/docs/docs/mediabunny/extract-thumbnail.mdx
+++ b/packages/docs/docs/mediabunny/extract-thumbnail.mdx
@@ -2,7 +2,7 @@
image: /generated/articles-docs-mediabunny-extract-thumbnail.png
title: Extracting a thumbnail from a video in JavaScript
crumb: 'Mediabunny'
-sidebar_label: Extracting thumbnail
+sidebar_label: Extracting a thumbnail
---
Extracting a single frame (thumbnail) from a video file can be done using [Mediabunny](https://mediabunny.dev).
@@ -19,154 +19,224 @@ export type ExtractThumbnailProps = {
};
export async function extractThumbnail({src, timestampInSeconds, signal}: ExtractThumbnailProps): Promise<VideoSample> {
- const input = new Input({
+ using input = new Input({
formats: ALL_FORMATS,
source: new UrlSource(src),
});
- const dispose = () => {
- input.dispose();
- };
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+ if (signal?.aborted) {
+ throw new Error('Aborted');
+ }
+
+ const sink = new VideoSampleSink(videoTrack);
+ const sampleIterator = sink.samplesAtTimestamps([timestampInSeconds]);
+ const sample = await sampleIterator.next();
- if (signal) {
- signal.addEventListener('abort', dispose, {once: true});
+ if (!sample.value) {
+ throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
}
- try {
- const videoTrack = await input.getPrimaryVideoTrack();
- if (!videoTrack) {
- throw new Error('No video track found in the input');
- }
+ return sample.value;
+}
+```
+
+## Example
- const sink = new VideoSampleSink(videoTrack);
+Here is how you can draw a thumbnail to a canvas:
- for await (const videoSample of sink.samplesAtTimestamps([timestampInSeconds])) {
- if (signal?.aborted) {
- throw new Error('Aborted');
- }
+```tsx twoslash
+import {ALL_FORMATS, Input, InputDisposedError, UrlSource, VideoSample, VideoSampleSink} from 'mediabunny';
- if (!videoSample) {
- throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
- }
+export type ExtractThumbnailProps = {
+ src: string;
+ timestampInSeconds: number;
+ signal?: AbortSignal;
+};
- return videoSample;
- }
+export async function extractThumbnail({src, timestampInSeconds, signal}: ExtractThumbnailProps): Promise<VideoSample> {
+ using input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
- throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
- } catch (error) {
- if (error instanceof InputDisposedError) {
- throw new Error('Input was disposed');
- }
-
- throw error;
- } finally {
- dispose();
- if (signal) {
- signal.removeEventListener('abort', dispose);
- }
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+ if (signal?.aborted) {
+ throw new Error('Aborted');
}
-}
-```
-## Usage
+ const sink = new VideoSampleSink(videoTrack);
+ const sampleIterator = sink.samplesAtTimestamps([timestampInSeconds]);
+ const sample = await sampleIterator.next();
-### Basic example: Extract a thumbnail at a specific time
+ if (!sample.value) {
+ throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
+ }
-```ts
+ return sample.value;
+}
+// ---cut---
const sample = await extractThumbnail({
src: 'https://remotion.media/video.mp4',
- timestampInSeconds: 5, // Extract frame at 5 seconds
+ timestampInSeconds: 5,
});
-// Convert sample to VideoFrame
-const frame = sample.toVideoFrame();
-
-// Draw frame to canvas
const canvas = document.createElement('canvas');
-canvas.width = frame.displayWidth;
-canvas.height = frame.displayHeight;
+canvas.width = sample.displayWidth;
+canvas.height = sample.displayHeight;
const ctx = canvas.getContext('2d');
-ctx.drawImage(frame, 0, 0);
-
-// Convert canvas to blob for display or download
-canvas.toBlob((blob) => {
- const url = URL.createObjectURL(blob);
- // Use the URL for displaying or downloading
-});
-
-// Don't forget to close the frame when done
-frame.close();
+sample.draw(ctx!, 0, 0);
+sample.close();
```
-### Extract thumbnail from the middle of a video
+## Memory management
-If you want to extract a frame from the middle of the video without knowing its duration beforehand, you can compute the duration first:
+The function returns a [`VideoSample`](https://mediabunny.dev/api/VideoSample#videosample) object. When it gets cleaned pup by garabge collection, it will be automatically closed, but a warning will be printed.
-```ts
-import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
+You can call [`.close()`](https://mediabunny.dev/api/VideoSample#close) to explicitly close the sample and prevent the warning from being printed.
-const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource('https://example.com/video.mp4'),
+```ts title="Explicitly closing a sample"
+using sample = await extractThumbnail({
+ src: 'https://example.com/video.mp4',
+ timestampInSeconds: 5,
});
-const durationInSeconds = await input.computeDuration();
-const middleTimestamp = durationInSeconds ? durationInSeconds / 2 : 0;
+sample.draw(ctx!, 0, 0);
+sample.close();
+```
-input.dispose();
+Or, you can use the [`using`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using) statement to clean up the sample when it goes out of scope.
-const sample = await extractThumbnail({
+```ts
+using sample = await extractThumbnail({
src: 'https://example.com/video.mp4',
- timestampInSeconds: middleTimestamp,
+ timestampInSeconds: 5,
});
-// Process the sample
-const frame = sample.toVideoFrame();
-// ... use the frame
-frame.close();
+sample.draw(ctx!, 0, 0);
```
-## Important notes
-
-### Memory management
+## Abort frame extraction
-The function returns a `VideoSample` object. You need to convert it to a `VideoFrame` using `.toVideoFrame()`, and always close the `VideoFrame` when you're done with it to prevent memory leaks:
+Pass an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to cancel thumbnail extraction:
-```ts
-const sample = await extractThumbnail({
- src: 'https://example.com/video.mp4',
- timestampInSeconds: 5,
-});
+```ts twoslash
+import {ALL_FORMATS, Input, InputDisposedError, UrlSource, VideoSample, VideoSampleSink} from 'mediabunny';
-const frame = sample.toVideoFrame();
+export type ExtractThumbnailProps = {
+ src: string;
+ timestampInSeconds: number;
+ signal?: AbortSignal;
+};
-// Use the frame
-ctx.drawImage(frame, 0, 0);
+export async function extractThumbnail({src, timestampInSeconds, signal}: ExtractThumbnailProps): Promise<VideoSample> {
+ using input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
-// Clean up
-frame.close();
-```
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+ if (signal?.aborted) {
+ throw new Error('Aborted');
+ }
-### Abort handling
+ const sink = new VideoSampleSink(videoTrack);
+ const sampleIterator = sink.samplesAtTimestamps([timestampInSeconds]);
+ const sample = await sampleIterator.next();
-Use an `AbortSignal` to cancel thumbnail extraction:
+ if (!sample.value) {
+ throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
+ }
-```ts
+ return sample.value;
+}
+// ---cut---
const controller = new AbortController();
-// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
- const sample = await extractThumbnail({
+ using sample = await extractThumbnail({
src: 'https://example.com/video.mp4',
timestampInSeconds: 10,
signal: controller.signal,
});
- const frame = sample.toVideoFrame();
- // Process frame
- frame.close();
+ console.log('Got frame!');
+} catch (error) {
+ console.error('Thumbnail extraction was aborted or failed:', error);
+}
+```
+
+## Setting a timeout
+
+Here is how you can set a maximum duration for extracting a thumbnail:
+
+```ts twoslash title="Fail if not able to extract within 5 seconds"
+import {ALL_FORMATS, Input, InputDisposedError, UrlSource, VideoSample, VideoSampleSink} from 'mediabunny';
+
+export type ExtractThumbnailProps = {
+ src: string;
+ timestampInSeconds: number;
+ signal?: AbortSignal;
+};
+
+export async function extractThumbnail({src, timestampInSeconds, signal}: ExtractThumbnailProps): Promise<VideoSample> {
+ using input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
+
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+ if (signal?.aborted) {
+ throw new Error('Aborted');
+ }
+
+ const sink = new VideoSampleSink(videoTrack);
+ const sampleIterator = sink.samplesAtTimestamps([timestampInSeconds]);
+ const sample = await sampleIterator.next();
+
+ if (!sample.value) {
+ throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
+ }
+
+ return sample.value;
+}
+// ---cut---
+const controller = new AbortController();
+
+const timeoutPromise = new Promise<never>((_, reject) => {
+ const timeoutId = setTimeout(() => {
+ controller.abort();
+ reject(new Error('Thumbnail extraction timed out after 5 seconds'));
+ }, 5000);
+
+ controller.signal.addEventListener('abort', () => clearTimeout(timeoutId), {once: true});
+});
+
+try {
+ using sample = await Promise.race([
+ extractThumbnail({
+ src: 'https://example.com/video.mp4',
+ timestampInSeconds: 10,
+ signal: controller.signal,
+ }),
+ timeoutPromise,
+ ]);
+
+ console.log('Got frame!');
} catch (error) {
console.error('Thumbnail extraction was aborted or failed:', error);
}
@@ -177,5 +247,5 @@ try {
- [Extracting video frames](/docs/mediabunny/extract-frames) - Extract multiple frames from a video
- [Mediabunny Documentation](https://mediabunny.dev)
- [Packets & samples in Mediabunny](https://mediabunny.dev/guide/packets-and-samples)
-- [VideoSampleSink API](https://mediabunny.dev/api/class/VideoSampleSink)
+- [`VideoSampleSink` API](https://mediabunny.dev/api/class/VideoSampleSink)
- [Supported formats](/docs/mediabunny/formats)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 1eef216ba3..ef206d00fc 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -1245,8 +1245,8 @@ const sidebars: SidebarsConfig = {
'mediabunny/index',
'mediabunny/new-video',
'mediabunny/metadata',
- 'mediabunny/extract-frames',
'mediabunny/extract-thumbnail',
+ 'mediabunny/extract-frames',
'mediabunny/can-decode',
'mediabunny/formats',
'mediabunny/version',