Skip to content

🎥 Make videos programmatically with React

Merge branch 'main' of https://github.com/remotion-dev/remotion into support/improve-user-uploads-docs

Igor Samokhovetsf0dfe2c2891f
diff --cc packages/docs/docs/video-uploads.mdx
index 51454113b1,30776a1a26..95bd83599e
--- a/packages/docs/docs/video-uploads.mdx
+++ b/packages/docs/docs/video-uploads.mdx
@@@ -135,205 -135,6 +135,208 @@@ As soon as possible, replace the `blob:
Since `blob:` URLs don't support the HTTP `Range` header, video seeking performance is degraded when using `blob:` URLs.
:::
+## Validating video compatibility
+
+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. 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 video before uploading:
+
+```ts twoslash title="can-decode.ts"
+import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
+
+export const canDecode = async (src: string) => {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new UrlSource(src),
+ });
+
+ try {
+ await input.getFormat();
+ } catch {
+ return false;
+ }
+
+ const videoTrack = await input.getPrimaryVideoTrack();
+ if (videoTrack && !(await videoTrack.canDecode())) {
+ return false;
+ }
+
+ const audioTrack = await input.getPrimaryAudioTrack();
+ if (audioTrack && !(await audioTrack.canDecode())) {
+ return false;
+ }
+
+ return true;
+};
+```
+
+### 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;
+};
+const upload = async (file: File) => {
+ return 'https://example.com/video.mp4';
+};
+const MyComposition: React.FC<{videoUrl: string}> = ({videoUrl}) => {
+ return null;
+};
+// ---cut---
+import {Player} from '@remotion/player';
+import {useCallback, useState} from 'react';
+
+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'});
+
+ const handleUpload = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+
+ try {
+ // Check if video can be decoded using blob URL
+ setState({type: 'validating'});
+ 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 {
++ if (!isCompatible) {
+ // 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;
+ }
++
++ // Video is compatible, upload directly
++ setState({type: 'uploading'});
++
++ const url = await upload(file);
++
++ setState({type: 'ready', url});
+ } catch (error) {
+ setState({type: 'error', message: 'Failed to process video'});
+ }
+ }, []);
+
+ return (
+ <div>
+ <input type="file" accept="video/*" onChange={handleUpload} />
+
+ {state.type === 'validating' && <p>Checking compatibility...</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>
+ );
+};
+```
+
+### 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)