Skip to content

🎥 Make videos programmatically with React

revert all the weird formatting

JonnyBurgerd73f1a10174e
diff --git a/packages/docs/docs/mediabunny/extract-frames.mdx b/packages/docs/docs/mediabunny/extract-frames.mdx
index c793eeb2d2..0c552b7391 100644
--- a/packages/docs/docs/mediabunny/extract-frames.mdx
+++ b/packages/docs/docs/mediabunny/extract-frames.mdx
@@ -10,102 +10,84 @@ Extracting frames from a video file, for example to display a filmstrip in an ed
Here's a `extractFrames()` function you can use copy and paste into your project:
```ts twoslash title="extract-frames.ts"
-import {
- ALL_FORMATS,
- Input,
- InputDisposedError,
- UrlSource,
- VideoSample,
- VideoSampleSink,
-} from 'mediabunny';
+import {ALL_FORMATS, Input, InputDisposedError, UrlSource, VideoSample, VideoSampleSink} from 'mediabunny';
type Options = {
- track: {width: number; height: number};
- container: string;
- durationInSeconds: number | null;
+ track: {width: number; height: number};
+ container: string;
+ durationInSeconds: number | null;
};
-export type ExtractFramesTimestampsInSecondsFn = (
- options: Options,
-) => Promise<number[]> | number[];
+export type ExtractFramesTimestampsInSecondsFn = (options: Options) => Promise<number[]> | number[];
export type ExtractFramesProps = {
- src: string;
- timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
- onVideoSample: (sample: VideoSample) => void;
- signal?: AbortSignal;
+ src: string;
+ timestampsInSeconds: number[] | ExtractFramesTimestampsInSecondsFn;
+ onVideoSample: (sample: VideoSample) => void;
+ signal?: AbortSignal;
};
-export async function extractFrames({
- src,
- timestampsInSeconds,
- onVideoSample,
- signal,
-}: ExtractFramesProps): Promise<void> {
- const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource(src),
- });
-
- const dispose = () => {
- input.dispose();
- };
-
- if (signal) {
- signal.addEventListener('abort', dispose, {once: true});
- }
-
- 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);
-
- for await (const videoSample of sink.samplesAtTimestamps(timestamps)) {
- if (signal?.aborted) {
- break;
- }
-
- if (!videoSample) {
- continue;
- }
-
- onVideoSample(videoSample);
- }
- } catch (error) {
- if (error instanceof InputDisposedError) {
- return;
- }
-
- throw error;
- } finally {
- dispose();
- if (signal) {
- signal.removeEventListener('abort', dispose);
- }
- }
+export async function extractFrames({src, timestampsInSeconds, onVideoSample, signal}: ExtractFramesProps): Promise<void> {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
+
+ const dispose = () => {
+ input.dispose();
+ };
+
+ if (signal) {
+ signal.addEventListener('abort', dispose, {once: true});
+ }
+
+ 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);
+
+ for await (const videoSample of sink.samplesAtTimestamps(timestamps)) {
+ if (signal?.aborted) {
+ break;
+ }
+
+ if (!videoSample) {
+ continue;
+ }
+
+ onVideoSample(videoSample);
+ }
+ } catch (error) {
+ if (error instanceof InputDisposedError) {
+ return;
+ }
+
+ throw error;
+ } finally {
+ dispose();
+ if (signal) {
+ signal.removeEventListener('abort', dispose);
+ }
+ }
}
```
@@ -115,22 +97,22 @@ export async function extractFrames({
```ts
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;
- const ctx = canvas.getContext('2d');
- ctx.drawImage(frame, 0, 0);
-
- // Don't forget to close the frame when done
- frame.close();
- },
+ 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;
+ const ctx = canvas.getContext('2d');
+ ctx.drawImage(frame, 0, 0);
+
+ // Don't forget to close the frame when done
+ frame.close();
+ },
});
```
@@ -145,33 +127,29 @@ 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;
- },
- onVideoSample: (sample) => {
- // Convert to VideoFrame if needed
- const frame = sample.toVideoFrame();
-
- // Process the frame
- console.log(`Frame at ${sample.timestamp}s`);
-
- // Clean up
- frame.close();
- },
+ 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;
+ },
+ onVideoSample: (sample) => {
+ // Convert to VideoFrame if needed
+ const frame = sample.toVideoFrame();
+
+ // Process the frame
+ console.log(`Frame at ${sample.timestamp}s`);
+
+ // Clean up
+ frame.close();
+ },
});
```
@@ -183,13 +161,13 @@ The `onVideoSample` callback receives a `VideoSample` object. You need to conver
```ts
onVideoSample: (sample) => {
- const frame = sample.toVideoFrame();
+ const frame = sample.toVideoFrame();
- // Use the frame
- ctx.drawImage(frame, 0, 0);
+ // Use the frame
+ ctx.drawImage(frame, 0, 0);
- // Clean up
- frame.close();
+ // Clean up
+ frame.close();
};
```
@@ -204,14 +182,14 @@ const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
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,
+ 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,
});
```
diff --git a/packages/docs/docs/mediabunny/extract-thumbnail.mdx b/packages/docs/docs/mediabunny/extract-thumbnail.mdx
index f0d56feec3..3b4c0f83a7 100644
--- a/packages/docs/docs/mediabunny/extract-thumbnail.mdx
+++ b/packages/docs/docs/mediabunny/extract-thumbnail.mdx
@@ -10,74 +10,61 @@ Extracting a single frame (thumbnail) from a video file can be done using [Media
Here's an `extractThumbnail()` function you can copy and paste into your project:
```ts twoslash title="extract-thumbnail.ts"
-import {
- ALL_FORMATS,
- Input,
- InputDisposedError,
- UrlSource,
- VideoSample,
- VideoSampleSink,
-} from 'mediabunny';
+import {ALL_FORMATS, Input, InputDisposedError, UrlSource, VideoSample, VideoSampleSink} from 'mediabunny';
export type ExtractThumbnailProps = {
- src: string;
- timestampInSeconds: number;
- signal?: AbortSignal;
+ src: string;
+ timestampInSeconds: number;
+ signal?: AbortSignal;
};
-export async function extractThumbnail({
- src,
- timestampInSeconds,
- signal,
-}: ExtractThumbnailProps): Promise<VideoSample> {
- const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource(src),
- });
-
- const dispose = () => {
- input.dispose();
- };
-
- if (signal) {
- signal.addEventListener('abort', dispose, {once: true});
- }
-
- try {
- const videoTrack = await input.getPrimaryVideoTrack();
- if (!videoTrack) {
- throw new Error('No video track found in the input');
- }
-
- const sink = new VideoSampleSink(videoTrack);
-
- for await (const videoSample of sink.samplesAtTimestamps([
- timestampInSeconds,
- ])) {
- if (signal?.aborted) {
- throw new Error('Aborted');
- }
-
- if (!videoSample) {
- throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
- }
-
- return videoSample;
- }
-
- 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);
- }
- }
+export async function extractThumbnail({src, timestampInSeconds, signal}: ExtractThumbnailProps): Promise<VideoSample> {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
+
+ const dispose = () => {
+ input.dispose();
+ };
+
+ if (signal) {
+ signal.addEventListener('abort', dispose, {once: true});
+ }
+
+ try {
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (!videoTrack) {
+ throw new Error('No video track found in the input');
+ }
+
+ const sink = new VideoSampleSink(videoTrack);
+
+ for await (const videoSample of sink.samplesAtTimestamps([timestampInSeconds])) {
+ if (signal?.aborted) {
+ throw new Error('Aborted');
+ }
+
+ if (!videoSample) {
+ throw new Error(`No frame found at timestamp ${timestampInSeconds}s`);
+ }
+
+ return videoSample;
+ }
+
+ 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);
+ }
+ }
}
```
@@ -87,8 +74,8 @@ export async function extractThumbnail({
```ts
const sample = await extractThumbnail({
- src: 'https://remotion.media/video.mp4',
- timestampInSeconds: 5, // Extract frame at 5 seconds
+ src: 'https://remotion.media/video.mp4',
+ timestampInSeconds: 5, // Extract frame at 5 seconds
});
// Convert sample to VideoFrame
@@ -103,8 +90,8 @@ 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
+ const url = URL.createObjectURL(blob);
+ // Use the URL for displaying or downloading
});
// Don't forget to close the frame when done
@@ -119,8 +106,8 @@ If you want to extract a frame from the middle of the video without knowing its
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
const input = new Input({
- formats: ALL_FORMATS,
- source: new UrlSource('https://example.com/video.mp4'),
+ formats: ALL_FORMATS,
+ source: new UrlSource('https://example.com/video.mp4'),
});
const durationInSeconds = await input.computeDuration();
@@ -129,8 +116,8 @@ const middleTimestamp = durationInSeconds ? durationInSeconds / 2 : 0;
input.dispose();
const sample = await extractThumbnail({
- src: 'https://example.com/video.mp4',
- timestampInSeconds: middleTimestamp,
+ src: 'https://example.com/video.mp4',
+ timestampInSeconds: middleTimestamp,
});
// Process the sample
@@ -147,8 +134,8 @@ The function returns a `VideoSample` object. You need to convert it to a `VideoF
```ts
const sample = await extractThumbnail({
- src: 'https://example.com/video.mp4',
- timestampInSeconds: 5,
+ src: 'https://example.com/video.mp4',
+ timestampInSeconds: 5,
});
const frame = sample.toVideoFrame();
@@ -171,17 +158,17 @@ const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
try {
- const sample = await extractThumbnail({
- src: 'https://example.com/video.mp4',
- timestampInSeconds: 10,
- signal: controller.signal,
- });
-
- const frame = sample.toVideoFrame();
- // Process frame
- frame.close();
+ const sample = await extractThumbnail({
+ src: 'https://example.com/video.mp4',
+ timestampInSeconds: 10,
+ signal: controller.signal,
+ });
+
+ const frame = sample.toVideoFrame();
+ // Process frame
+ frame.close();
} catch (error) {
- console.error('Thumbnail extraction was aborted or failed:', error);
+ console.error('Thumbnail extraction was aborted or failed:', error);
}
```