🎥 Make videos programmatically with React
Skills: Add Canvas Capture import via experimental-codemod
Jonny Burger11963a122b8f
diff --git a/.agents/skills/import-canvas-capture/SKILL.md b/.agents/skills/import-canvas-capture/SKILL.mdnew file mode 100644index 0000000000..9960b85421--- /dev/null+++ b/.agents/skills/import-canvas-capture/SKILL.md@@ -0,0 +1,69 @@+---+name: import-canvas-capture+description: Import a recorded Remotion Canvas Capture into a project without Studio interactions using the internal experimental-codemod command. Use when adding a capture file as an editable composition with cursor keyframes.+---++# Import Canvas Capture++This is an internal, unstable workflow. Keep this skill in `.agents/skills`; do+not distribute it through `packages/skills` or document the command as a stable API.++## Workflow++1. Locate the recorded capture file and the target Remotion project. The original+ recording must contain embedded `REMOTION_CAPTURE_DATA` metadata; a converted+ video that has lost this metadata cannot be imported.+2. Inspect the project to find the TypeScript file containing its composition+ registrations (usually `src/Root.tsx`). Choose an unused composition ID.+3. From the target project's root, run:++ ```sh+ bunx remotion experimental-codemod add-canvas-capture /absolute/path/capture.webm \+ --composition-file src/Root.tsx \+ --id MyCapture+ ```++ When developing this command in the monorepo, build the CLI first with+ `bun run build`, then invoke the local CLI from the target project's root:++ ```sh+ node /absolute/path/to/remotion/packages/cli/remotion-cli.js \+ experimental-codemod add-canvas-capture /absolute/path/capture.webm \+ --composition-file src/Root.tsx --id MyCapture+ ```++4. Review the reported source files and public asset. The importer generates a+ component beside the registration file, registers it, copies the video to the+ public directory, and installs missing `@remotion/media` and+ `@remotion/mac-cursors` dependencies at the project's Remotion version. Studio+ does not need to be running. Existing Studio sessions pick up source changes+ through their file watchers; this operation does not enter Studio's undo stack.+5. Report the composition ID and changed files to the user.++## Options and conflicts++- Defaults match Studio's capture import: 1920×1080, 60 fps, and duration rounded+ up from the recording. Pass `--width`, `--height`, or `--fps` to override them.+ Recorded video dimensions remain independent from composition dimensions.+- `--public-dir` overrides the configured public directory. `--package-manager`+ selects the dependency installer.+- `--dry-run` parses the recording and generates source changes without installing+ dependencies or writing project files. The programmatic result includes the+ proposed source changes.+- The registration file is resolved relative to the project root; the CLI capture+ path is resolved relative to the current working directory.+- Existing component files and conflicting public assets are rejected. If the+ recording is already in the public directory, pass that file as the input to+ reuse it. Otherwise rename the input or select another composition ID; do not+ overwrite an existing asset or component to bypass an error.++## Programmatic access++Use `CliInternals.importCanvasCapture` from `@remotion/cli`. It is internal and+unstable. Its inputs are `captureFile`, `compositionFile`, `compositionId`,+`remotionRoot`, `publicDir`, `fps`, `width`, `height`, `packageManager`, `logLevel`,+and `dryRun`. Supply `null` for default directory, dimensions, frame rate, and+package manager. File paths are resolved relative to `remotionRoot`.++The result contains the composition ID, source and asset paths, composition+metadata, and codemod changes. Pass `dryRun: true` to inspect changes in memory.diff --git a/bun.lock b/bun.lockindex c7ba17e8a9..47982d6ceb 100644--- a/bun.lock+++ b/bun.lock@@ -282,6 +282,7 @@"dependencies": {"@babel/parser": "7.24.1","@remotion/bundler": "workspace:*",+ "@remotion/codemods": "workspace:*","@remotion/media-utils": "workspace:*","@remotion/player": "workspace:*","@remotion/renderer": "workspace:*",@@ -289,6 +290,7 @@"@remotion/studio-server": "workspace:*","@remotion/studio-shared": "workspace:*","dotenv": "17.3.1",+ "mediabunny": "catalog:","minimist": "1.2.6","prompts": "2.4.2","remotion": "workspace:*",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex bd3804c114..88faa3adc0 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -38,6 +38,7 @@"dependencies": {"@babel/parser": "7.24.1","@remotion/bundler": "workspace:*",+ "@remotion/codemods": "workspace:*","@remotion/media-utils": "workspace:*","@remotion/player": "workspace:*","@remotion/renderer": "workspace:*",@@ -45,6 +46,7 @@"@remotion/studio-server": "workspace:*","@remotion/studio": "workspace:*","dotenv": "17.3.1",+ "mediabunny": "catalog:","minimist": "1.2.6","prompts": "2.4.2","semver": "7.5.3",diff --git a/packages/cli/src/experimental-codemod.ts b/packages/cli/src/experimental-codemod.tsnew file mode 100644index 0000000000..d0427c6564--- /dev/null+++ b/packages/cli/src/experimental-codemod.ts@@ -0,0 +1,98 @@+import path from 'node:path';+import type {LogLevel} from '@remotion/renderer';+import {BrowserSafeApis} from '@remotion/renderer/client';+import minimist from 'minimist';+import {importCanvasCapture} from './import-canvas-capture';+import {Log} from './log';++export const printExperimentalCodemodHelp = (logLevel: LogLevel) => {+ Log.info(+ {indent: false, logLevel},+ [+ 'Internal, unstable command. Arguments and behavior may change without notice.',+ '',+ 'bunx remotion experimental-codemod add-canvas-capture <file> --composition-file <Root.tsx> --id <composition-id>',+ '',+ '--width <pixels> Composition width (default: 1920)',+ '--height <pixels> Composition height (default: 1080)',+ '--fps <number> Composition and cursor keyframe FPS (default: 60)',+ '--public-dir <path> Public directory (default: configured directory or public/)',+ '--package-manager <name> Package manager used to install runtime dependencies',+ '--dry-run Generate changes without installing packages or writing files',+ ].join('\n'),+ );+};++export const experimentalCodemodCommand = async (+ remotionRoot: string,+ argv: string[],+ logLevel: LogLevel,+) => {+ const commandLine = minimist(argv, {+ string: ['_', 'composition-file', 'id'],+ boolean: ['dry-run', 'help'],+ });+ const [, command, captureFile] = commandLine._;+ if (commandLine.help || command === undefined) {+ printExperimentalCodemodHelp(logLevel);+ return;+ }++ if (command !== 'add-canvas-capture') {+ throw new Error(+ `Unknown experimental codemod: ${command}. Use experimental-codemod --help.`,+ );+ }++ const compositionFile = commandLine['composition-file'];+ const compositionId = commandLine.id;+ if (+ commandLine._.length !== 3 ||+ typeof captureFile !== 'string' ||+ !captureFile ||+ typeof compositionFile !== 'string' ||+ !compositionFile ||+ typeof compositionId !== 'string' ||+ !compositionId+ ) {+ throw new Error(+ 'Usage: bunx remotion experimental-codemod add-canvas-capture <file> --composition-file <Root.tsx> --id <composition-id>',+ );+ }++ Log.warn(+ {indent: false, logLevel},+ 'experimental-codemod is internal and unstable. Arguments and behavior may change without notice.',+ );+ const {+ overrideWidthOption,+ overrideHeightOption,+ overrideFpsOption,+ publicDirOption,+ packageManagerOption,+ } = BrowserSafeApis.options;+ const result = await importCanvasCapture({+ captureFile: path.resolve(captureFile),+ compositionFile,+ compositionId,+ remotionRoot,+ publicDir: publicDirOption.getValue({commandLine}).value,+ width: overrideWidthOption.getValue({commandLine}).value,+ height: overrideHeightOption.getValue({commandLine}).value,+ fps: overrideFpsOption.getValue({commandLine}).value,+ packageManager: packageManagerOption.getValue({commandLine}).value,+ logLevel,+ dryRun: commandLine['dry-run'],+ });+ Log.info(+ {indent: false, logLevel},+ `${commandLine['dry-run'] ? 'Would import' : 'Imported'} Canvas Capture as "${result.compositionId}" (${result.metadata.width}×${result.metadata.height}, ${result.metadata.fps} fps, ${result.metadata.durationInFrames} frames)`,+ );+ for (const file of [+ result.compositionFile,+ result.componentFile,+ result.videoFile,+ ]) {+ Log.info({indent: false, logLevel}, path.relative(remotionRoot, file));+ }+};diff --git a/packages/cli/src/import-canvas-capture.ts b/packages/cli/src/import-canvas-capture.tsnew file mode 100644index 0000000000..75f811c2cb--- /dev/null+++ b/packages/cli/src/import-canvas-capture.ts@@ -0,0 +1,247 @@+import {randomUUID} from 'node:crypto';+import {constants, existsSync} from 'node:fs';+import {+ copyFile,+ mkdir,+ open,+ readFile,+ realpath,+ rename,+ rm,+ stat,+ writeFile,+} from 'node:fs/promises';+import path from 'node:path';+import {addCanvasCaptureComposition} from '@remotion/codemods';+import type {LogLevel} from '@remotion/renderer';+import {+ parseCanvasCaptureData,+ type CanvasCaptureData,+} from '@remotion/studio-shared';+import {ALL_FORMATS, FilePathSource, Input} from 'mediabunny';+import {addCommand} from './add';++// Internal and unstable. Keep the file import separate from the pure codemod.+export const importCanvasCapture = async ({+ captureFile,+ compositionFile,+ compositionId,+ remotionRoot,+ publicDir,+ fps,+ width,+ height,+ packageManager,+ logLevel,+ dryRun,+}: {+ captureFile: string;+ compositionFile: string;+ compositionId: string;+ remotionRoot: string;+ publicDir: string | null;+ fps: number | null;+ width: number | null;+ height: number | null;+ packageManager: string | null;+ logLevel: LogLevel;+ dryRun: boolean;+}) => {+ const rootDir = path.resolve(remotionRoot);+ const registrationFile = await realpath(+ path.resolve(rootDir, compositionFile),+ );+ if (!/\.tsx?$/.test(registrationFile)) {+ throw new Error(+ 'The composition file must be a TypeScript file (.ts or .tsx)',+ );+ }++ const words = compositionId.match(/[a-zA-Z0-9]+/g) ?? [];+ const name = words+ .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)+ .join('');+ const componentName = `${/^[0-9]/.test(name) ? 'Capture' : ''}${name || 'CanvasCapture'}Composition`;+ const componentFile = path.join(+ path.dirname(registrationFile),+ `${componentName}.tsx`,+ );+ if (existsSync(componentFile)) {+ throw new Error(`Cannot create ${componentFile} because it already exists`);+ }++ const videoSource = await realpath(path.resolve(rootDir, captureFile));+ const videoFileName = path.basename(captureFile);+ const videoFile = path.resolve(rootDir, publicDir ?? 'public', videoFileName);+ const existingVideo = existsSync(videoFile)+ ? await realpath(videoFile)+ : null;+ if (existingVideo !== null && existingVideo !== videoSource) {+ throw new Error(+ `Cannot copy the capture because ${videoFile} already exists. Rename the capture or use the file already in the public directory.`,+ );+ }++ const input = new Input({+ formats: ALL_FORMATS,+ source: new FilePathSource(videoSource),+ });++ let capture: {+ data: CanvasCaptureData;+ videoWidth: number;+ videoHeight: number;+ durationInSeconds: number;+ };+ try {+ const [tags, videoTrack] = await Promise.all([+ input.getMetadataTags(),+ input.getPrimaryVideoTrack(),+ ]);+ const data = parseCanvasCaptureData(tags);+ if (data === null) {+ throw new Error(+ 'The file does not contain valid REMOTION_CAPTURE_DATA metadata',+ );+ }++ if (videoTrack === null) {+ throw new Error('The Canvas Capture does not contain a video track');+ }++ const [durationFromMetadata, videoWidth, videoHeight] = await Promise.all([+ input.getDurationFromMetadata(),+ videoTrack.getDisplayWidth(),+ videoTrack.getDisplayHeight(),+ ]);+ const durationInSeconds =+ durationFromMetadata ?? (await input.computeDuration([videoTrack]));+ if (+ [durationInSeconds, videoWidth, videoHeight].some(+ (value) => !Number.isFinite(value) || value <= 0,+ )+ ) {+ throw new Error('The Canvas Capture has invalid duration or dimensions');+ }++ capture = {data, videoWidth, videoHeight, durationInSeconds};+ } finally {+ input.dispose();+ }++ const metadata = {+ width: width ?? 1920,+ height: height ?? 1080,+ fps: fps ?? 60,+ durationInFrames: Math.max(+ 1,+ Math.ceil(capture.durationInSeconds * (fps ?? 60)),+ ),+ };+ const previousContents = await readFile(registrationFile, 'utf-8');+ const result = addCanvasCaptureComposition({+ project: {rootDir, files: {[registrationFile]: previousContents}},+ compositionFile: registrationFile,+ compositionId,+ component: {+ filePath: componentFile,+ importName: componentName,+ importPath: `./${componentName}`,+ },+ metadata,+ capture: {+ data: capture.data,+ keyframeFps: metadata.fps,+ videoFileName,+ videoWidth: capture.videoWidth,+ videoHeight: capture.videoHeight,+ },+ });+ const registrationContents = result.changes.find(+ (change) => change.filePath === registrationFile,+ )?.nextContents;+ const componentContents = result.changes.find(+ (change) => change.filePath === componentFile,+ )?.nextContents;+ if (+ typeof registrationContents !== 'string' ||+ typeof componentContents !== 'string'+ ) {+ throw new Error(+ 'The Canvas Capture codemod did not generate both source files',+ );+ }++ if (!dryRun) {+ await addCommand({+ remotionRoot: rootDir,+ packageManager: packageManager ?? undefined,+ packageNames: ['@remotion/media', '@remotion/mac-cursors'],+ logLevel,+ args: [],+ });++ const temporaryFile = path.join(+ path.dirname(registrationFile),+ `.remotion-capture-${randomUUID()}.tmp`,+ );+ let createdVideo = false;+ let createdComponent = false;+ try {+ if ((await readFile(registrationFile, 'utf-8')) !== previousContents) {+ throw new Error(+ `Source changed before importing the capture: ${registrationFile}`,+ );+ }++ if (existingVideo === null) {+ await mkdir(path.dirname(videoFile), {recursive: true});+ await copyFile(videoSource, videoFile, constants.COPYFILE_EXCL);+ createdVideo = true;+ }++ const componentHandle = await open(componentFile, 'wx');+ createdComponent = true;++ try {+ await componentHandle.writeFile(componentContents, 'utf-8');+ } finally {+ await componentHandle.close();+ }++ const {mode} = await stat(registrationFile);+ await writeFile(temporaryFile, registrationContents, {+ encoding: 'utf-8',+ flag: 'wx',+ mode,+ });+ if ((await readFile(registrationFile, 'utf-8')) !== previousContents) {+ throw new Error(+ `Source changed before importing the capture: ${registrationFile}`,+ );+ }++ await rename(temporaryFile, registrationFile);+ } catch (error) {+ await rm(temporaryFile, {force: true});+ if (createdComponent) {+ await rm(componentFile, {force: true});+ }++ if (createdVideo) {+ await rm(videoFile, {force: true});+ }++ throw error;+ }+ }++ return {+ compositionId,+ compositionFile: registrationFile,+ componentFile,+ videoFile,+ metadata,+ ...result,+ };+};diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 8cbb3f9fcb..37e9152b89 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -20,6 +20,10 @@ import {listCompositionsCommand} from './compositions';import {determineFinalStillImageFormat} from './determine-image-format';import {getFileSizeDownloadBar} from './download-progress';import {findEntryPoint} from './entry-point';+import {+ experimentalCodemodCommand,+ printExperimentalCodemodHelp,+} from './experimental-codemod';import {ffmpegCommand, ffprobeCommand} from './ffmpeg';import {getCliOptions} from './get-cli-options';import {getCompositionWithDimensionOverride} from './get-composition-with-dimension-override';@@ -28,6 +32,7 @@ import {getGitSource} from './get-github-repository';import {gpuCommand} from './gpu';import {supportsHyperlink} from './hyperlinks/is-supported';import {makeHyperlink} from './hyperlinks/make-link';+import {importCanvasCapture} from './import-canvas-capture';import {initializeCli} from './initialize-cli';import {lambdaCommand, tryPrintLambdaHelp} from './lambda-command';import {listOfRemotionPackages} from './list-of-remotion-packages';@@ -65,6 +70,11 @@ export const cli = async () => {: parsedCli._;if (parsedCli.help || command === 'help') {const [helpCommand, ...helpArgs] = helpPath;+ if (helpCommand === 'experimental-codemod') {+ printExperimentalCodemodHelp('info');+ return;+ }+if (helpCommand === 'lambda' || helpCommand === 'cloudrun') {const helpRemotionRoot = RenderInternals.findRemotionRoot();const printed =@@ -175,6 +185,12 @@ export const cli = async () => {cwd: process.cwd(),environment: process.env,});+ } else if (command === 'experimental-codemod') {+ await experimentalCodemodCommand(+ remotionRoot,+ process.argv.slice(2),+ logLevel,+ );} else if (command === VERSIONS_COMMAND) {await versionsCommand(remotionRoot, logLevel);} else if (command === BROWSER_COMMAND) {@@ -201,6 +217,7 @@ export const cli = async () => {};export const CliInternals = {+ importCanvasCapture,createOverwriteableCliOutput,chalk,makeProgressBar,diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonindex aecbd92b10..4d0580b16f 100644--- a/packages/cli/tsconfig.json+++ b/packages/cli/tsconfig.json@@ -12,6 +12,7 @@"references": [{"path": "../core"},{"path": "../bundler"},+ {"path": "../codemods"},{"path": "../renderer"},{"path": "../player"},{"path": "../media-utils"},