Skip to content

🎥 Make videos programmatically with React

address Jonny's feedback

Igor Samokhovetsa01f3919a701
diff --git a/packages/docs/docs/video-uploads.mdx b/packages/docs/docs/video-uploads.mdx
index 67c5831a18..51454113b1 100644
--- a/packages/docs/docs/video-uploads.mdx
+++ b/packages/docs/docs/video-uploads.mdx
@@ -137,15 +137,15 @@ Since `blob:` URLs don't support the HTTP `Range` header, video seeking performa
## Validating video compatibility
-After a user uploads a video, you should validate whether the browser can decode it. The recommended best practice is:
+Before uploading a video, you should validate whether the browser can decode it. This saves bandwidth and provides immediate feedback to the user. The recommended best practice is:
-1. Use Mediabunny's [canDecode()](/docs/mediabunny/can-decode) function to check if the video can be played
-2. If it can be decoded, use the video directly
+1. Check the video locally using a blob URL with Mediabunny's [canDecode()](/docs/mediabunny/can-decode) function
+2. If it can be decoded, upload it to the cloud
3. If it cannot be decoded, either re-encode it with FFmpeg or reject the upload
### Check if video can be decoded
-Use the `canDecode()` snippet to validate the uploaded video:
+Use the `canDecode()` snippet to validate the video before uploading:
```ts twoslash title="can-decode.ts"
import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
@@ -176,36 +176,10 @@ export const canDecode = async (src: string) => {
};
```
-### Handle incompatible videos
-
-If a video cannot be decoded, re-encode it using FFmpeg:
-
-```ts title="reencode.ts"
-import {execa} from 'execa';
-
-export const reencodeVideo = async (inputPath: string, outputPath: string) => {
- await execa('ffmpeg', [
- '-i',
- inputPath,
- '-c:v',
- 'libx264', // H.264 video codec (widely supported)
- '-preset',
- 'fast',
- '-crf',
- '23',
- '-c:a',
- 'aac', // AAC audio codec
- '-b:a',
- '128k',
- outputPath,
- ]);
-
- return outputPath;
-};
-```
-
### Complete example with validation
+This example validates the video locally before uploading, then either uploads it directly or sends it to a re-encoding API endpoint:
+
```tsx twoslash title="ValidatedUploader.tsx"
const canDecode = async (src: string) => {
return true;
@@ -213,9 +187,6 @@ const canDecode = async (src: string) => {
const upload = async (file: File) => {
return 'https://example.com/video.mp4';
};
-const reencodeVideo = async (src: string) => {
- return 'https://example.com/reencoded.mp4';
-};
const MyComposition: React.FC<{videoUrl: string}> = ({videoUrl}) => {
return null;
};
@@ -223,7 +194,7 @@ const MyComposition: React.FC<{videoUrl: string}> = ({videoUrl}) => {
import {Player} from '@remotion/player';
import {useCallback, useState} from 'react';
-type UploadState = {type: 'idle'} | {type: 'uploading'} | {type: 'validating'} | {type: 'reencoding'} | {type: 'ready'; url: string} | {type: 'error'; message: string};
+type UploadState = {type: 'idle'} | {type: 'validating'} | {type: 'uploading'} | {type: 'reencoding'} | {type: 'ready'; url: string} | {type: 'error'; message: string};
export const ValidatedUploader: React.FC = () => {
const [state, setState] = useState<UploadState>({type: 'idle'});
@@ -233,21 +204,31 @@ export const ValidatedUploader: React.FC = () => {
if (!file) return;
try {
- setState({type: 'uploading'});
- const url = await upload(file);
-
+ // Check if video can be decoded using blob URL
setState({type: 'validating'});
- const isCompatible = await canDecode(url);
+ const blobUrl = URL.createObjectURL(file);
+ const isCompatible = await canDecode(blobUrl);
+ URL.revokeObjectURL(blobUrl);
if (isCompatible) {
+ // Video is compatible, upload directly
+ setState({type: 'uploading'});
+ const url = await upload(file);
+ setState({type: 'ready', url});
+ } else {
+ // Video needs re-encoding
+ setState({type: 'reencoding'});
+ const formData = new FormData();
+ formData.append('video', file);
+
+ const response = await fetch('/api/reencode-video', {
+ method: 'POST',
+ body: formData,
+ });
+
+ const {url} = await response.json();
setState({type: 'ready', url});
- return;
}
-
- // Re-encode incompatible videos
- setState({type: 'reencoding'});
- const reencodedUrl = await reencodeVideo(url);
- setState({type: 'ready', url: reencodedUrl});
} catch (error) {
setState({type: 'error', message: 'Failed to process video'});
}
@@ -257,9 +238,9 @@ export const ValidatedUploader: React.FC = () => {
<div>
<input type="file" accept="video/*" onChange={handleUpload} />
- {state.type === 'uploading' && <p>Uploading...</p>}
{state.type === 'validating' && <p>Checking compatibility...</p>}
- {state.type === 'reencoding' && <p>Re-encoding video...</p>}
+ {state.type === 'uploading' && <p>Uploading...</p>}
+ {state.type === 'reencoding' && <p>Re-encoding and uploading...</p>}
{state.type === 'error' && <p>Error: {state.message}</p>}
{state.type === 'ready' && <Player component={MyComposition} durationInFrames={120} compositionWidth={1920} compositionHeight={1080} fps={30} inputProps={{videoUrl: state.url}} />}
</div>
@@ -267,6 +248,92 @@ export const ValidatedUploader: React.FC = () => {
};
```
+### Server-side re-encoding API
+
+Create an API endpoint that receives the video, re-encodes it using FFmpeg, and returns the URL:
+
+```ts title="server.ts"
+import express from 'express';
+import multer from 'multer';
+import {execa} from 'execa';
+import path from 'path';
+import fs from 'fs/promises';
+
+const app = express();
+const upload = multer({dest: 'uploads/'});
+
+app.post('/api/reencode-video', upload.single('video'), async (req, res) => {
+ if (!req.file) {
+ return res.status(400).json({error: 'No video file provided'});
+ }
+
+ const inputPath = req.file.path;
+ const outputPath = path.join('uploads', `reencoded-${Date.now()}.mp4`);
+
+ try {
+ await execa('ffmpeg', [
+ '-i',
+ inputPath,
+ '-c:v',
+ 'libx264', // H.264 video codec (widely supported)
+ '-preset',
+ 'fast',
+ '-crf',
+ '23',
+ '-c:a',
+ 'aac',
+ '-b:a',
+ '128k',
+ outputPath,
+ ]);
+
+ // Upload re-encoded video to cloud storage
+ // This is provider-specific (S3, GCS, etc.)
+ const cloudUrl = await uploadToCloud(outputPath);
+
+ // Clean up temporary files
+ await fs.unlink(inputPath);
+ await fs.unlink(outputPath);
+
+ res.json({url: cloudUrl});
+ } catch (error) {
+ // Clean up on error
+ await fs.unlink(inputPath).catch(() => {});
+ await fs.unlink(outputPath).catch(() => {});
+
+ res.status(500).json({error: 'Failed to re-encode video'});
+ }
+});
+
+// Example cloud upload function (implementation depends on your provider)
+async function uploadToCloud(filePath: string): Promise<string> {
+ // Example using AWS S3:
+ // const fileContent = await fs.readFile(filePath);
+ // const s3 = new S3Client({region: 'us-east-1'});
+ // await s3.send(new PutObjectCommand({
+ // Bucket: 'my-bucket',
+ // Key: `videos/${path.basename(filePath)}`,
+ // Body: fileContent,
+ // }));
+ // return `https://my-bucket.s3.amazonaws.com/videos/${path.basename(filePath)}`;
+
+ return `https://example.com/videos/${path.basename(filePath)}`;
+}
+
+app.listen(3000, () => {
+ console.log('Server running on port 3000');
+});
+```
+
+The API endpoint:
+
+1. Receives the video file via multipart form data
+2. Saves it temporarily using multer
+3. Re-encodes it with FFmpeg to H.264/AAC format
+4. Uploads the re-encoded video to cloud storage
+5. Cleans up temporary files
+6. Returns the cloud URL to the client
+
## See also
- [Uploading with presigned URLs](/docs/presigned-urls)