Skip to content

🎥 Make videos programmatically with React

check

Hunain Ahmed0be23b0cfd38
diff --git a/packages/core/bundle.ts b/packages/core/bundle.ts
index 0be455d6e9..dfbf4a50c4 100644
--- a/packages/core/bundle.ts
+++ b/packages/core/bundle.ts
@@ -16,7 +16,7 @@ const output = await build({
entrypoints: ['src/index.ts'],
naming: '[name].mjs',
target: 'browser',
- external: ['remotion', 'remotion/no-react', 'react', 'react-dom'],
+ external: ['remotion', 'remotion/no-react', 'react', 'react-dom', '@remotion/webcodecs'],
});
const [file] = output.outputs;
@@ -36,7 +36,7 @@ const noReactOutput = await build({
entrypoints: ['src/no-react.ts'],
naming: '[name].mjs',
target: 'browser',
- external: ['remotion', 'react', 'react-dom'],
+ external: ['remotion', 'react', 'react-dom', '@remotion/webcodecs'],
});
const [noReactFile] = noReactOutput.outputs;
await Bun.write('dist/esm/no-react.mjs', await noReactFile.text());
diff --git a/packages/core/package.json b/packages/core/package.json
index 92601ac49d..0d6e711fb7 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -24,6 +24,9 @@
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
+ "dependencies": {
+ "@remotion/webcodecs": "workspace:*"
+ },
"devDependencies": {
"@testing-library/react": "16.1.0",
"@testing-library/dom": "10.4.0",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c350078f0b..0a5d0fc099 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -136,6 +136,11 @@ export * from './internals.js';
export {interpolateColors} from './interpolate-colors.js';
export {LogLevel} from './log.js';
export {Loop} from './loop/index.js';
+export {validateMediaProps} from './validate-media-props.js'
+export {resolveTrimProps, validateMediaTrimProps} from './validate-start-from-props.js'
+export {VideoForPreview} from './video/VideoForPreview.js'
+export {OffthreadVideoForRendering} from './video/OffthreadVideoForRendering.js'
+export {CodecVideoForRendering} from './video/codecVideoForRendering.js'
export {
EasingFunction,
ExtrapolateType,
@@ -159,6 +164,8 @@ export * from './spring/index.js';
export {staticFile} from './static-file.js';
export * from './Still.js';
export type {PlayableMediaTag} from './timeline-position-state.js';
+export {useUnsafeVideoConfig} from './use-unsafe-video-config.js'
+export type {RemotionOffthreadVideoProps} from './video/props.js'
export {useBufferState} from './use-buffer-state';
export {useCurrentFrame} from './use-current-frame.js';
export {
diff --git a/packages/core/src/video/codecVideoForRendering.tsx b/packages/core/src/video/codecVideoForRendering.tsx
new file mode 100644
index 0000000000..ef7766c6e9
--- /dev/null
+++ b/packages/core/src/video/codecVideoForRendering.tsx
@@ -0,0 +1,149 @@
+import React, { useLayoutEffect, useRef } from 'react';
+import {extractFrames} from '@remotion/webcodecs'
+import type {RemotionOffthreadVideoProps} from './props.js';
+import { useUnsafeVideoConfig } from '../use-unsafe-video-config.js';
+import { useCurrentFrame } from '../use-current-frame.js';
+import { continueRender, delayRender } from '../delay-render.js';
+// import { useMediaStartsAt } from '../audio/use-audio-frame.js';
+
+export const CodecVideoForRendering: React.FC<
+ RemotionOffthreadVideoProps
+> = ({
+ // onError,
+ // volume: volumeProp,
+ // playbackRate,
+ src,
+ // muted,
+ // allowAmplificationDuringRender,
+ // transparent = false,
+ // toneMapped = true,
+ // toneFrequency,
+ // name,
+ // loopVolumeCurveBehavior,
+ delayRenderRetries,
+ delayRenderTimeoutInMilliseconds,
+ //call when a frame of the video, i.e. img is rendered
+ // onVideoFrame,
+ // // Remove crossOrigin prop during rendering
+ // // https://discord.com/channels/809501355504959528/844143007183667220/1311639632496033813
+ // crossOrigin,
+ // ...props
+}) => {
+ // const absoluteFrame = useTimelinePosition();
+
+ // const frame = useCurrentFrame();
+ // const volumePropsFrame = useFrameForVolumeProp(
+ // loopVolumeCurveBehavior ?? 'repeat',
+ // );
+ const videoConfig = useUnsafeVideoConfig();
+ // const sequenceContext = useContext(SequenceContext);
+ // const mediaStartsAt = useMediaStartsAt();
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ // const [frames, setframes] = useState<VideoFrame[]>([]);
+ const frame = useCurrentFrame();
+
+ if (!videoConfig) {
+ throw new Error('No video config found');
+ }
+ // const currentTime = useMemo(() => {
+ // return (
+ // getExpectedMediaFrameUncorrected({
+ // frame,
+ // playbackRate: playbackRate || 1,
+ // startFrom: -mediaStartsAt,
+ // }) / videoConfig.fps
+ // );
+ // }, [frame, mediaStartsAt, playbackRate, videoConfig.fps]);
+
+ // const {registerRenderAsset, unregisterRenderAsset} =
+ // useContext(RenderAssetManager);
+
+ if (!src) {
+ throw new TypeError('No `src` was passed to <CodecVideo>.');
+ }
+
+ //retrive the active frame with useFrame hook
+ //get the current time of the renderer
+ //whenever current time changes, search through frames to find the most relevant frame
+ //draw the frame on the canvas
+
+ //PLAN FOR CONCURRENCY SUPPORT
+ // do something so that activeFrame is determined solely based on frame
+ // like write frame'th index of frames to the canvas
+
+ // useEffect(()=>{
+ // console.log("called for frame " + frame)
+ // if(!canvasRef.current){
+ // console.log("returning because no ref current")
+ // return
+ // };
+
+ // // if(frames.length === 0){
+ // // console.log("returning because no frames")
+ // // return
+ // // }
+
+ // // let activeFrame = frames[frame];
+ // // let activeFrame=frames.find(frame => (
+ // // (frame.timestamp / 1000000) >= currentTime
+ // // ));
+
+ // // if(!activeFrame){
+ // // console.log(`returning, you tried fetching index ${frame} of frames which is not available yet `);
+ // // console.log(`frames available: ${frames.length}`)
+ // // return;
+ // // }
+
+ // //get the col index
+
+ // //approach:
+ // //1. delayrender
+ // //2. extract individual frame
+ // //3. continue
+ // const newH
+ // console.log("WRITING FRAME AT INDEX " , frame);
+
+ // canvasRef.current.getContext("2d")?.drawImage(activeFrame,0,0)
+ // }, [frame, canvasRef])
+
+
+
+
+ useLayoutEffect(()=>{
+ if(!canvasRef.current){
+ return;
+ }
+ // 1 : 30
+ // x : frame
+ console.log("called for frame "+ frame)
+ const newHandle = delayRender(`extracting frame number ${frame}`, {
+ retries: delayRenderRetries ?? undefined,
+ timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
+ });
+
+ extractFrames({
+ src,
+ timestampsInSeconds: async ({track}) => {
+ if(!track.fps){
+ return [];
+ }
+ console.log(`called for frame ${frame} with timestamp ${frame/track.fps}`)
+ return [frame/track.fps]
+ },
+ onFrame: (extractedFrame) => {
+ console.log("successfully extracted the frame " + frame);
+ //render the canvas
+ canvasRef.current?.getContext("2d")?.drawImage(extractedFrame,0, 0);
+ extractedFrame.close()
+ //continue render
+ continueRender(newHandle)
+ },
+ })
+
+
+ },[frame])
+
+ return (
+ <canvas width={videoConfig.width} height={videoConfig.height} ref={canvasRef} />
+ );
+};
diff --git a/packages/example/package.json b/packages/example/package.json
index d3203be06c..edd2366358 100644
--- a/packages/example/package.json
+++ b/packages/example/package.json
@@ -35,6 +35,7 @@
"@remotion/animated-emoji": "workspace:*",
"@remotion/animation-utils": "workspace:*",
"@remotion/babel-loader": "workspace:*",
+ "@remotion/video": "workspace:*",
"@remotion/webcodecs": "workspace:*",
"@remotion/bundler": "workspace:*",
"@remotion/cli": "workspace:*",
diff --git a/packages/example/src/OffthreadVideoToCanvas/index.tsx b/packages/example/src/OffthreadVideoToCanvas/index.tsx
index 0150eaacda..f0ffd4b371 100644
--- a/packages/example/src/OffthreadVideoToCanvas/index.tsx
+++ b/packages/example/src/OffthreadVideoToCanvas/index.tsx
@@ -1,10 +1,10 @@
import {useCallback, useRef} from 'react';
import {
AbsoluteFill,
- OffthreadVideo,
staticFile,
useVideoConfig,
} from 'remotion';
+import {CodecVideo} from '@remotion/video'
export const OffthreadVideoToCanvas: React.FC = () => {
const canvas = useRef<HTMLCanvasElement>(null);
@@ -12,6 +12,7 @@ export const OffthreadVideoToCanvas: React.FC = () => {
const onVideoFrame = useCallback(
(frame: CanvasImageSource) => {
+ console.log("frame new ", frame)
if (!canvas.current) {
return;
}
@@ -21,38 +22,36 @@ export const OffthreadVideoToCanvas: React.FC = () => {
return;
}
- context.drawImage(frame, 0, 0, width, height);
- const imageFrame = context.getImageData(0, 0, width, height);
- const {length} = imageFrame.data;
+ // context.drawImage(frame, 0, 0, width, height);
+ // const imageFrame = context.getImageData(0, 0, width, height);
+ // const {length} = imageFrame.data;
// If the pixel is very green, reduce the alpha channel
- for (let i = 0; i < length; i += 4) {
- const red = imageFrame.data[i + 0];
- const green = imageFrame.data[i + 1];
- const blue = imageFrame.data[i + 2];
+ // for (let i = 0; i < length; i += 4) {
+ // const red = imageFrame.data[i + 0];
+ // const green = imageFrame.data[i + 1];
+ // const blue = imageFrame.data[i + 2];
- imageFrame.data[i + 0] = 255 - red;
- imageFrame.data[i + 1] = 255 - green;
- imageFrame.data[i + 2] = 255 - blue;
- }
- context.putImageData(imageFrame, 0, 0);
+ // imageFrame.data[i + 0] = 255 - red;
+ // imageFrame.data[i + 1] = 255 - green;
+ // imageFrame.data[i + 2] = 255 - blue;
+ // }
+ // context.putImageData(imageFrame, 0, 0);
},
[height, width],
);
return (
<AbsoluteFill style={{}}>
- <AbsoluteFill>
- <OffthreadVideo
- muted
- style={{opacity: 0}}
+ <CodecVideo
+ // muted
+ // style={{opacity: 0}}
src={staticFile('vid1.mp4')}
- onVideoFrame={onVideoFrame}
+ // onVideoFrame={onVideoFrame}
/>
- </AbsoluteFill>
- <AbsoluteFill>
+ {/* <AbsoluteFill>
<canvas ref={canvas} width={width} height={height} />
- </AbsoluteFill>
+ </AbsoluteFill> */}
</AbsoluteFill>
);
};
diff --git a/packages/video/README.md b/packages/video/README.md
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/video/bundle.ts b/packages/video/bundle.ts
new file mode 100644
index 0000000000..2f79e94aa5
--- /dev/null
+++ b/packages/video/bundle.ts
@@ -0,0 +1,30 @@
+import {build} from 'bun';
+import path from 'path';
+
+if (process.env.NODE_ENV !== 'production') {
+ throw new Error('This script must be run using NODE_ENV=production');
+}
+console.time('Generated.');
+const output = await build({
+ entrypoints: [
+ 'src/index.ts'
+ ],
+ naming: '[name].mjs',
+ external: ['@remotion/webcodecs', 'remotion', 'react', 'react-dom'],
+});
+
+if (!output.success) {
+ console.log(output.logs.join('\n'));
+ process.exit(1);
+}
+
+for (const file of output.outputs) {
+ const str = await file.text();
+ const out = path.join('dist', 'esm', file.path);
+
+ await Bun.write(out, str);
+}
+
+
+
+console.timeEnd('Generated.');
diff --git a/packages/video/eslint.config.mjs b/packages/video/eslint.config.mjs
new file mode 100644
index 0000000000..93a5fc215f
--- /dev/null
+++ b/packages/video/eslint.config.mjs
@@ -0,0 +1,5 @@
+import {remotionFlatConfig} from '@remotion/eslint-config-internal';
+
+const config = remotionFlatConfig({react: true});
+
+export default config;
diff --git a/packages/video/package.json b/packages/video/package.json
new file mode 100644
index 0000000000..ee15baa4a3
--- /dev/null
+++ b/packages/video/package.json
@@ -0,0 +1,46 @@
+{
+ "name": "@remotion/video",
+ "version": "4.0.324",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "module": "dist/esm/index.mjs",
+ "sideEffects": false,
+ "bugs": {
+ "url": "https://github.com/remotion-dev/remotion/issues"
+ },
+ "scripts": {
+ "formatting": "prettier --experimental-cli src --check",
+ "lint": "eslint src",
+ "test": "bun test src/test",
+ "watch": "tsc -w",
+ "make": "tsc -d && bun --env-file=../.env.bundle bundle.ts"
+ },
+ "dependencies": {
+ "remotion": "workspace:*",
+ "@remotion/webcodecs": "workspace:*"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "react-dom": ">=16.8.0"
+ },
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "eslint": "9.19.0",
+ "react": "19.0.0",
+ "react-dom": "19.0.0"
+ },
+ "keywords": [],
+ "publishConfig": {
+ "access": "public"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "require": "./dist/index.js",
+ "module": "./dist/esm/index.mjs",
+ "import": "./dist/esm/index.mjs"
+ },
+ "./package.json": "./package.json"
+ },
+ "description": "off thread video"
+}
diff --git a/packages/video/src/index.ts b/packages/video/src/index.ts
new file mode 100644
index 0000000000..461a67e0af
--- /dev/null
+++ b/packages/video/src/index.ts
@@ -0,0 +1 @@
+export * from './video'
\ No newline at end of file
diff --git a/packages/video/src/video.tsx b/packages/video/src/video.tsx
new file mode 100644
index 0000000000..00d4d0ace5
--- /dev/null
+++ b/packages/video/src/video.tsx
@@ -0,0 +1,102 @@
+import React, {useCallback} from 'react';
+import { CodecVideoForRendering, getRemotionEnvironment, RemotionOffthreadVideoProps, resolveTrimProps, Sequence, validateMediaProps, validateMediaTrimProps, VideoForPreview } from 'remotion'
+
+/*
+ * @description This method imports and displays a video, similar to <Video />. During rendering, it extracts the exact frame from the video and displays it in an <img> tag
+ * @see [Documentation](https://www.remotion.dev/docs/offthreadvideo)
+ */
+export const CodecVideo: React.FC<RemotionOffthreadVideoProps> = (
+ props,
+) => {
+ // Should only destruct `startFrom` and `endAt` from props,
+ // rest gets drilled down
+ const {
+ startFrom,
+ endAt,
+ trimBefore,
+ trimAfter,
+ name,
+ pauseWhenBuffering,
+ stack,
+ showInTimeline,
+ ...otherProps
+ } = props;
+ const environment = getRemotionEnvironment();
+
+ const onDuration = useCallback(() => undefined, []);
+
+ if (typeof props.src !== 'string') {
+ throw new TypeError(
+ `The \`<OffthreadVideo>\` tag requires a string for \`src\`, but got ${JSON.stringify(
+ props.src,
+ )} instead.`,
+ );
+ }
+
+ if (props.imageFormat) {
+ throw new TypeError(
+ `The \`<OffthreadVideo>\` tag does no longer accept \`imageFormat\`. Use the \`transparent\` prop if you want to render a transparent video.`,
+ );
+ }
+
+ validateMediaTrimProps({startFrom, endAt, trimBefore, trimAfter});
+
+ const {trimBeforeValue, trimAfterValue} = resolveTrimProps({
+ startFrom,
+ endAt,
+ trimBefore,
+ trimAfter,
+ });
+
+ if (
+ typeof trimBeforeValue !== 'undefined' ||
+ typeof trimAfterValue !== 'undefined'
+ ) {
+ return (
+ <Sequence
+ layout="none"
+ from={0 - (trimBeforeValue ?? 0)}
+ showInTimeline={false}
+ durationInFrames={trimAfterValue}
+ name={name}
+ >
+ <CodecVideo
+ pauseWhenBuffering={pauseWhenBuffering ?? false}
+ {...otherProps}
+ />
+ </Sequence>
+ );
+ }
+
+ validateMediaProps(props, 'Video');
+
+ if (environment.isRendering) {
+ return <CodecVideoForRendering {...otherProps} />;
+ }
+
+ const {
+ transparent,
+ toneMapped,
+ onAutoPlayError,
+ onVideoFrame,
+ crossOrigin,
+ delayRenderRetries,
+ delayRenderTimeoutInMilliseconds,
+ ...propsForPreview
+ } = otherProps;
+
+ return (
+ <VideoForPreview
+ _remotionInternalStack={stack ?? null}
+ _remotionInternalNativeLoopPassed={false}
+ onDuration={onDuration}
+ onlyWarnForMediaSeekingError
+ pauseWhenBuffering={pauseWhenBuffering ?? false}
+ showInTimeline={showInTimeline ?? true}
+ onAutoPlayError={onAutoPlayError ?? undefined}
+ onVideoFrame={onVideoFrame ?? null}
+ crossOrigin={crossOrigin}
+ {...propsForPreview}
+ />
+ );
+};
diff --git a/packages/video/tsconfig.json b/packages/video/tsconfig.json
new file mode 100644
index 0000000000..164d5dc077
--- /dev/null
+++ b/packages/video/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "extends": "../tsconfig.settings.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist",
+ "jsx": "react-jsx",
+ "skipLibCheck": true,
+ "target": "ES2020"
+ },
+ "include": ["src"],
+ "references": [
+ {
+ "path": "../webcodecs"
+ }
+ ]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0b050a49c6..2d1e160748 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -469,6 +469,10 @@ importers:
packages/core:
+ dependencies:
+ '@remotion/webcodecs':
+ specifier: workspace:*
+ version: link:../webcodecs
devDependencies:
'@happy-dom/global-registrator':
specifier: 14.5.1
@@ -1073,6 +1077,9 @@ importers:
'@remotion/transitions':
specifier: workspace:*
version: link:../transitions
+ '@remotion/video':
+ specifier: workspace:*
+ version: link:../video
'@remotion/webcodecs':
specifier: workspace:*
version: link:../webcodecs
@@ -3650,6 +3657,28 @@ importers:
specifier: 19.0.0
version: 19.0.0([email protected])
+ packages/video:
+ dependencies:
+ '@remotion/webcodecs':
+ specifier: workspace:*
+ version: link:../webcodecs
+ remotion:
+ specifier: workspace:*
+ version: link:../core
+ devDependencies:
+ '@remotion/eslint-config-internal':
+ specifier: workspace:*
+ version: link:../eslint-config-internal
+ eslint:
+ specifier: 9.19.0
+ version: 9.19.0
+ react:
+ specifier: 19.0.0
+ version: 19.0.0
+ react-dom:
+ specifier: 19.0.0
+ version: 19.0.0([email protected])
+
packages/webcodecs:
dependencies:
'@remotion/licensing':