Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add Generate captions quick action for media

Jonny Burger9de0d68a92b4
diff --git a/bun.lock b/bun.lock
index 544cdbafb0..6c50200519 100644
--- a/bun.lock
+++ b/bun.lock
@@ -250,6 +250,12 @@
"@remotion/eslint-config-internal": "workspace:*",
"@typescript/native-preview": "catalog:",
"eslint": "catalog:",
+ "react": "catalog:",
+ "remotion": "workspace:*",
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "remotion": "workspace:*",
},
},
"packages/claude-code-plugin": {
@@ -10673,6 +10679,8 @@
"@remotion/canvas/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
+ "@remotion/captions/react": ["[email protected]", "", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],
+
"@remotion/cli/react": ["[email protected]", "", {}, "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA=="],
"@remotion/cli/react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.3" } }, "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg=="],
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index a3ecc97f50..b52e4b55da 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -14,6 +14,7 @@ import {
getFolderFile,
getRootFileForProject,
insertJsxElementIntoProjectWithNodePathRemappings,
+ insertBasicCaptions as insertBasicCaptionsCodemod,
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
makeInMemoryInsertJsxElementCodemodEnvironment,
@@ -1902,6 +1903,50 @@ export const createBrowserStudioOperations = ({
}
};
+ const insertBasicCaptions: BrowserStudioOperations['insertBasicCaptions'] = ({
+ fileName,
+ nodePath,
+ captions,
+ durationInFrames,
+ }) => {
+ try {
+ const project = getProject();
+ const absolutePath = findProjectFile({filePath: fileName, project});
+ const result = insertBasicCaptionsCodemod({
+ input: project.files[absolutePath],
+ nodePath,
+ captions,
+ durationInFrames,
+ });
+ const nodePathMutation = controller.applyMutation({
+ undoRedoNavigation: null,
+ timelineSelection: null,
+ fileName: absolutePath,
+ mutate: () => ({
+ ...project,
+ files: {...project.files, [absolutePath]: result.output},
+ }),
+ nodePathMutationFiles: [
+ {
+ absolutePath,
+ remappings: result.nodePathRemappings,
+ },
+ ],
+ });
+ if (nodePathMutation === null) {
+ throw new Error('Could not insert Basic captions');
+ }
+
+ return Promise.resolve({success: true as const, nodePathMutation});
+ } catch (error) {
+ return Promise.resolve({
+ success: false as const,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error && error.stack ? error.stack : '',
+ });
+ }
+ };
+
const insertJsxElement: BrowserStudioOperations['insertJsxElement'] = async (
request,
) => {
@@ -2352,6 +2397,7 @@ export const createBrowserStudioOperations = ({
refreshSequencePropsSubscriptions();
},
splitVideoFromAudio,
+ insertBasicCaptions,
subscribeToDefaultProps: ({clientId, compositionId}) => {
const clients =
defaultPropsSubscriptions.get(compositionId) ?? new Set<string>();
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index d4014836c5..0759a3aa6a 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -325,7 +325,7 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
).toBe(false);
});
-test('splits video from audio, broadcasts remappings and supports undo', async () => {
+test('splits video audio and inserts captions with remappings and undo', async () => {
const fileName = '/project/src/Composition.tsx';
const initialSource = `import {Video} from '@remotion/media';
export const Component = () => <Video src="video.mp4" from={10} durationInFrames={20} volume={0.5} style={{opacity: 0.5}} />;`;
@@ -402,6 +402,39 @@ registerRoot(Root);`,
const undoResult = await operations.undo();
expect(undoResult.success).toBe(true);
expect(currentProject.files[fileName]).toBe(initialSource);
+
+ events.length = 0;
+ const captionsResult = await operations.insertBasicCaptions({
+ fileName: 'src/Composition.tsx',
+ nodePath: subscription.nodePath.nodePath,
+ durationInFrames: 20,
+ captions: [
+ {
+ text: ' Hello',
+ startMs: 100,
+ endMs: 500,
+ timestampMs: 300,
+ confidence: null,
+ },
+ ],
+ });
+ if (!captionsResult.success) {
+ throw new Error(captionsResult.reason);
+ }
+
+ expect(currentProject.files[fileName]).toContain(
+ "import {BasicCaptions} from '@remotion/captions/basic-captions';",
+ );
+ expect(currentProject.files[fileName]).toContain(
+ '<BasicCaptions captions={[',
+ );
+ expect(currentProject.files[fileName]).toContain('"text": " Hello"');
+ expect(events).toContainEqual({
+ type: 'sequence-node-paths-remapped',
+ mutation: captionsResult.nodePathMutation,
+ });
+ expect((await operations.undo()).success).toBe(true);
+ expect(currentProject.files[fileName]).toBe(initialSource);
});
test('reports invalid timeline Solid input without changing the project', async () => {
diff --git a/packages/captions/bundle.ts b/packages/captions/bundle.ts
index 24f8465e8e..6e6e687cfa 100644
--- a/packages/captions/bundle.ts
+++ b/packages/captions/bundle.ts
@@ -14,4 +14,14 @@ const text = await file.text();
await Bun.write('dist/esm/index.mjs', text);
+const basicCaptions = await build({
+ entrypoints: ['src/basic-captions.tsx'],
+ naming: '[name].mjs',
+ external: ['react', 'react/jsx-runtime', 'remotion'],
+});
+await Bun.write(
+ 'dist/esm/basic-captions.mjs',
+ await basicCaptions.outputs[0].text(),
+);
+
export {};
diff --git a/packages/captions/package.json b/packages/captions/package.json
index 2580d3a4b9..9729a127a5 100644
--- a/packages/captions/package.json
+++ b/packages/captions/package.json
@@ -21,10 +21,15 @@
"author": "Jonny Burger <[email protected]>",
"license": "MIT",
"dependencies": {},
- "peerDependencies": {},
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "remotion": "workspace:*"
+ },
"devDependencies": {
"@remotion/eslint-config-internal": "workspace:*",
"eslint": "catalog:",
+ "react": "catalog:",
+ "remotion": "workspace:*",
"@typescript/native-preview": "catalog:"
},
"keywords": [
@@ -32,6 +37,12 @@
],
"exports": {
"./package.json": "./package.json",
+ "./basic-captions": {
+ "types": "./dist/basic-captions.d.ts",
+ "module": "./dist/esm/basic-captions.mjs",
+ "import": "./dist/esm/basic-captions.mjs",
+ "require": "./dist/basic-captions.js"
+ },
".": {
"types": "./dist/index.d.ts",
"module": "./dist/esm/index.mjs",
diff --git a/packages/captions/src/basic-captions.tsx b/packages/captions/src/basic-captions.tsx
new file mode 100644
index 0000000000..af8c7d58c9
--- /dev/null
+++ b/packages/captions/src/basic-captions.tsx
@@ -0,0 +1,174 @@
+import React, {forwardRef, useImperativeHandle, useMemo, useRef} from 'react';
+import {
+ Interactive,
+ Sequence,
+ useCurrentFrame,
+ useVideoConfig,
+ type InteractiveBaseProps,
+ type InteractiveTransformProps,
+ type InteractivitySchema,
+ type SequenceControls,
+ type SequenceProps,
+} from 'remotion';
+import type {Caption} from './caption';
+import {createTikTokStyleCaptions} from './create-tiktok-style-captions';
+
+export type BasicCaptionsProps = InteractiveBaseProps &
+ InteractiveTransformProps &
+ Pick<
+ SequenceProps,
+ 'from' | 'durationInFrames' | 'trimBefore' | 'width' | 'height'
+ > & {
+ readonly captions: Caption[];
+ readonly playbackRate?: number;
+ readonly combineTokensWithinMilliseconds?: number;
+ };
+
+const CaptionContent: React.FC<
+ Pick<
+ BasicCaptionsProps,
+ 'captions' | 'playbackRate' | 'combineTokensWithinMilliseconds'
+ >
+> = ({captions, playbackRate = 1, combineTokensWithinMilliseconds = 2000}) => {
+ const frame = useCurrentFrame();
+ const {fps} = useVideoConfig();
+ const pages = useMemo(
+ () =>
+ createTikTokStyleCaptions({
+ captions,
+ combineTokensWithinMilliseconds,
+ }).pages,
+ [captions, combineTokensWithinMilliseconds],
+ );
+ const currentTimeMs = (frame / fps) * 1000 * playbackRate;
+ const page = pages.find(
+ (candidate) =>
+ currentTimeMs >= candidate.startMs &&
+ currentTimeMs < candidate.startMs + candidate.durationMs,
+ );
+
+ if (!page) {
+ return null;
+ }
+
+ return (
+ <div
+ style={{
+ backgroundColor: 'rgba(64, 64, 64, 0.75)',
+ color: '#ffffff',
+ display: '-webkit-box',
+ fontFamily: 'Arial, Helvetica, sans-serif',
+ fontSize: 64,
+ fontWeight: 400,
+ lineHeight: 1.2,
+ overflow: 'hidden',
+ padding: '14px 22px',
+ textAlign: 'center',
+ textWrap: 'balance',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: 2,
+ whiteSpace: 'pre-wrap',
+ }}
+ >
+ {page.text.trim()}
+ </div>
+ );
+};
+
+const basicCaptionsSchema = {
+ ...Interactive.baseSchema,
+ ...Interactive.captionsSchema,
+ width: {
+ type: 'number',
+ min: 1,
+ step: 1,
+ default: undefined,
+ description: 'Caption area width',
+ hiddenFromList: false,
+ },
+ height: {
+ type: 'number',
+ min: 1,
+ step: 1,
+ default: undefined,
+ description: 'Caption area height',
+ hiddenFromList: false,
+ },
+ combineTokensWithinMilliseconds: {
+ type: 'number',
+ min: 0,
+ step: 50,
+ default: 2000,
+ description: 'Time between caption pages',
+ hiddenFromList: false,
+ },
+ ...Interactive.transformSchema,
+} as const satisfies InteractivitySchema;
+
+const BasicCaptionsInner = forwardRef<
+ HTMLDivElement,
+ BasicCaptionsProps & {readonly controls: SequenceControls | undefined}
+>(
+ (
+ {
+ captions,
+ combineTokensWithinMilliseconds,
+ controls,
+ durationInFrames,
+ from,
+ height = 220,
+ name,
+ playbackRate,
+ style,
+ trimBefore,
+ width = 900,
+ ...interactiveProps
+ },
+ ref,
+ ) => {
+ const outlineRef = useRef<HTMLDivElement>(null);
+ useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);
+
+ return (
+ <Sequence
+ layout="none"
+ {...interactiveProps}
+ controls={controls}
+ name={name ?? 'Basic captions'}
+ from={from}
+ durationInFrames={durationInFrames}
+ trimBefore={trimBefore}
+ outlineRef={outlineRef}
+ >
+ <div
+ ref={outlineRef}
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ justifyContent: 'center',
+ position: 'absolute',
+ bottom: 120,
+ left: '50%',
+ transform: 'translateX(-50%)',
+ width,
+ height,
+ ...style,
+ }}
+ >
+ <CaptionContent
+ captions={captions}
+ combineTokensWithinMilliseconds={combineTokensWithinMilliseconds}
+ playbackRate={playbackRate}
+ />
+ </div>
+ </Sequence>
+ );
+ },
+);
+
+export const BasicCaptions = Interactive.withSchema({
+ Component: BasicCaptionsInner,
+ componentName: '<BasicCaptions>',
+ schema: basicCaptionsSchema,
+ supportsEffects: false,
+}) as React.FC<BasicCaptionsProps>;
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index 8d7730a291..662560a904 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -85,6 +85,7 @@ export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-no
export {simpleDiff} from './simple-diff';
export {splitJsxSequence} from './split-jsx-sequence';
export {splitVideoFromAudio} from './split-video-from-audio';
+export {insertBasicCaptions} from './insert-basic-captions';
export {
getCompositionDefaultPropsLine,
updateDefaultProps,
diff --git a/packages/studio-codemods/src/insert-basic-captions.ts b/packages/studio-codemods/src/insert-basic-captions.ts
new file mode 100644
index 0000000000..374ec149dd
--- /dev/null
+++ b/packages/studio-codemods/src/insert-basic-captions.ts
@@ -0,0 +1,208 @@
+import type {JSXElement, JSXFragment} from '@babel/types';
+import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
+import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
+import {findJsxElementPathForDeletion} from './delete-jsx-node';
+import {
+ captureJsxNodePaths,
+ getNodePathRemappings,
+} from './get-node-path-remappings';
+import {indentInsertedJsx} from './print-jsx';
+import {recastLocToOffset} from './recast-loc-to-offset';
+import {ensureNamedImport, getImportedName} from './sequence-props/imports';
+import {parseAst} from './sequence-props/parse-ast';
+import {
+ applySourceEdits,
+ captureImportSnapshots,
+ getAdjacentJsxInsertionSourceEdit,
+ getInsertImportSourceEdits,
+ getJsxElementSourceForInsertion,
+} from './source-edits';
+import {
+ getEndOfLine,
+ getIndentationUnit,
+ getLineIndent,
+ indentContinuationLines,
+} from './source-style';
+
+export const insertBasicCaptions = ({
+ input,
+ nodePath,
+ captions,
+ durationInFrames,
+ prettierConfigOverride = null,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ captions: {
+ text: string;
+ startMs: number;
+ endMs: number;
+ timestampMs: number | null;
+ confidence: number | null;
+ pageBreakAfter?: boolean;
+ }[];
+ durationInFrames: number | null;
+ prettierConfigOverride?: Record<string, unknown> | null;
+}): {
+ output: string;
+ logLine: number;
+ nodePathRemappings: SequenceNodePathRemapping[];
+} => {
+ const ast = parseAst(input);
+ const captured = captureJsxNodePaths(ast);
+ const importSnapshots = captureImportSnapshots(ast);
+ const mediaPath = findJsxElementPathForDeletion(ast, nodePath);
+ if (!mediaPath) {
+ throw new Error('Could not find the selected audio or video element');
+ }
+
+ const media = mediaPath.node as JSXElement;
+ if (media.openingElement.name.type !== 'JSXIdentifier') {
+ throw new Error('The selected media tag cannot be transcribed');
+ }
+
+ const tagName = media.openingElement.name.name;
+ const importedMedia = ast.program.body.some(
+ (statement) =>
+ statement.type === 'ImportDeclaration' &&
+ statement.importKind !== 'type' &&
+ (statement.source.value === 'remotion' ||
+ statement.source.value === '@remotion/media') &&
+ statement.specifiers.some(
+ (specifier) =>
+ specifier.type === 'ImportSpecifier' &&
+ specifier.local.name === tagName &&
+ [
+ 'Video',
+ 'Audio',
+ 'OffthreadVideo',
+ 'experimental_Video',
+ 'experimental_Audio',
+ ].includes(getImportedName(specifier)),
+ ),
+ );
+ if (!importedMedia) {
+ throw new Error('The selected element is not a Remotion Video or Audio');
+ }
+
+ let localName = 'BasicCaptions';
+ let suffix = 1;
+ while (new RegExp(`\\b${localName}\\b`).test(input)) {
+ localName = `BasicCaptions${suffix++}`;
+ }
+
+ const captionsLocalName = ensureNamedImport({
+ ast,
+ importedName: 'BasicCaptions',
+ localName,
+ sourcePath: '@remotion/captions/basic-captions',
+ });
+ const copiedAttributes = media.openingElement.attributes
+ .filter(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ ['from', 'durationInFrames', 'trimBefore', 'playbackRate'].includes(
+ attribute.name.name,
+ ),
+ )
+ .map((attribute) => recast.print(attribute).code);
+ if (
+ Number.isFinite(durationInFrames) &&
+ durationInFrames !== null &&
+ !copiedAttributes.some((attribute) =>
+ attribute.startsWith('durationInFrames'),
+ )
+ ) {
+ copiedAttributes.push(`durationInFrames={${durationInFrames}}`);
+ }
+
+ const elementSource = `<${captionsLocalName} captions={${JSON.stringify(captions, null, 2)}} ${copiedAttributes.join(' ')} />`;
+ const parsedElement = parseAst(`const element = (${elementSource});`).program
+ .body[0];
+ if (
+ parsedElement?.type !== 'VariableDeclaration' ||
+ parsedElement.declarations[0]?.init?.type !== 'JSXElement'
+ ) {
+ throw new Error('Could not generate the Basic captions element');
+ }
+
+ const inserted = parsedElement.declarations[0].init;
+ const parent = mediaPath.parentPath?.node;
+ if (!parent) {
+ throw new Error('Could not locate the media element parent');
+ }
+
+ let sourceEdit;
+ if (
+ (parent.type === 'JSXElement' || parent.type === 'JSXFragment') &&
+ parent.children.includes(media)
+ ) {
+ const index = parent.children.indexOf(media);
+ parent.children.splice(index + 1, 0, inserted);
+ sourceEdit = getAdjacentJsxInsertionSourceEdit({
+ input,
+ insertion: elementSource,
+ position: 'after',
+ target: media,
+ });
+ } else {
+ const fragment: JSXFragment = {
+ type: 'JSXFragment',
+ openingFragment: {type: 'JSXOpeningFragment'},
+ closingFragment: {type: 'JSXClosingFragment'},
+ children: [media, inserted],
+ };
+ mediaPath.replace(fragment);
+ if (!media.loc) {
+ throw new Error('Could not locate the media element in source');
+ }
+
+ const start = recastLocToOffset(input, media.loc.start);
+ const end = recastLocToOffset(input, media.loc.end);
+ const indent = getLineIndent({input, offset: start});
+ const unit = getIndentationUnit(input, prettierConfigOverride);
+ const eol = getEndOfLine(input);
+ sourceEdit = {
+ start,
+ end,
+ replacement: indentContinuationLines({
+ indent,
+ input,
+ printed: [
+ '<>',
+ indentInsertedJsx({
+ indent: unit,
+ insertion: getJsxElementSourceForInsertion({element: media, input}),
+ }),
+ indentInsertedJsx({indent: unit, insertion: elementSource}),
+ '</>',
+ ].join(eol),
+ }),
+ };
+ }
+
+ const output = applySourceEdits({
+ input,
+ edits: [
+ ...getInsertImportSourceEdits({
+ ast,
+ input,
+ prettierConfigOverride,
+ snapshots: importSnapshots,
+ }),
+ sourceEdit,
+ ],
+ });
+ const {nodePathRemappings} = getNodePathRemappings({
+ ast,
+ captured,
+ output,
+ });
+ return {
+ output,
+ logLine: media.openingElement.loc?.start.line ?? 1,
+ nodePathRemappings,
+ };
+};
diff --git a/packages/studio-server/src/codemods/insert-basic-captions.ts b/packages/studio-server/src/codemods/insert-basic-captions.ts
new file mode 100644
index 0000000000..22bfc8371b
--- /dev/null
+++ b/packages/studio-server/src/codemods/insert-basic-captions.ts
@@ -0,0 +1 @@
+export {insertBasicCaptions} from '@remotion/studio-codemods';
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index f7d22d2862..5ecb29f436 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -25,6 +25,7 @@ import {downloadRemoteAssetHandler} from './routes/download-remote-asset';
import {duplicateEffectHandler} from './routes/duplicate-effect';
import {duplicateJsxNodeHandler} from './routes/duplicate-jsx-node';
import {findInFileHandler} from './routes/find-in-file';
+import {insertBasicCaptionsHandler} from './routes/insert-basic-captions';
import {insertElementHandler} from './routes/insert-element';
import {insertJsxElementHandler} from './routes/insert-jsx-element';
import {
@@ -128,6 +129,7 @@ export const allApiRoutes: {
'/api/duplicate-jsx-node': duplicateJsxNodeHandler,
'/api/split-jsx-sequence': splitJsxSequenceHandler,
'/api/split-video-from-audio': splitVideoFromAudioHandler,
+ '/api/insert-basic-captions': insertBasicCaptionsHandler,
'/api/update-available': handleUpdate,
'/api/release-notes': getReleaseNotesHandler,
'/api/remotion-skills-info': remotionSkillsInfoHandler,
diff --git a/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts b/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
new file mode 100644
index 0000000000..3c9eb547d8
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/insert-basic-captions.ts
@@ -0,0 +1,91 @@
+import {readFileSync} from 'node:fs';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ InsertBasicCaptionsRequest,
+ InsertBasicCaptionsResponse,
+} from '@remotion/studio-shared';
+import {insertBasicCaptions} from '../../codemods/insert-basic-captions';
+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
+import type {ApiHandler} from '../api-types';
+import {formatLogFileLocation} from '../format-log-file-location';
+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';
+import {
+ printUndoHint,
+ pushToUndoStack,
+ suppressUndoStackInvalidation,
+} from '../undo-stack';
+import {
+ getCodemodTimingPrefix,
+ withSourceFileWriteQueue,
+} from './source-file-write-queue';
+
+export const insertBasicCaptionsHandler: ApiHandler<
+ InsertBasicCaptionsRequest,
+ InsertBasicCaptionsResponse
+> = ({
+ input: {fileName, nodePath, captions, durationInFrames},
+ remotionRoot,
+ logLevel,
+}) =>
+ withSourceFileWriteQueue<InsertBasicCaptionsResponse>(() => {
+ try {
+ const {absolutePath} = resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'modify',
+ });
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const {output, logLine, nodePathRemappings} = insertBasicCaptions({
+ input: fileContents,
+ nodePath,
+ captions,
+ durationInFrames,
+ });
+ const nodePathMutation = broadcastSequenceNodePathMutation(
+ [{absolutePath, remappings: nodePathRemappings}],
+ null,
+ );
+
+ pushToUndoStack({
+ filePath: absolutePath,
+ oldContents: fileContents,
+ newContents: null,
+ logLevel,
+ remotionRoot,
+ logLine,
+ description: {
+ undoMessage: '↩️ Insertion of Basic captions',
+ redoMessage: '↪️ Insertion of Basic captions',
+ },
+ entryType: 'insert-basic-captions',
+ suppressHmrOnFileRestore: false,
+ nodePathRemappings,
+ });
+ suppressUndoStackInvalidation(absolutePath);
+ writeFileAndNotifyFileWatchers({
+ file: absolutePath,
+ content: output,
+ originatorClientId: undefined,
+ metadata: {skipSequencePropsUpdate: true},
+ });
+
+ const locationLabel = formatLogFileLocation({
+ remotionRoot,
+ absolutePath,
+ line: logLine,
+ });
+ RenderInternals.Log.info(
+ {indent: false, logLevel},
+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Inserted Basic captions`,
+ );
+ printUndoHint(logLevel);
+ return Promise.resolve({success: true as const, nodePathMutation});
+ } catch (error) {
+ return Promise.resolve({
+ success: false,
+ reason: (error as Error).message,
+ stack: (error as Error).stack ?? '',
+ } as const);
+ }
+ });
diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.ts
index 7d65aa4b8d..dc73309521 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -42,6 +42,7 @@ type UndoEntryType =
| 'duplicate-jsx-node'
| 'split-jsx-sequence'
| 'split-video-from-audio'
+ | 'insert-basic-captions'
| 'insert-jsx-element'
| 'delete-composition'
| 'rename-composition'
diff --git a/packages/studio-server/src/test/insert-basic-captions.test.ts b/packages/studio-server/src/test/insert-basic-captions.test.ts
new file mode 100644
index 0000000000..d2ac769bce
--- /dev/null
+++ b/packages/studio-server/src/test/insert-basic-captions.test.ts
@@ -0,0 +1,126 @@
+import {expect, test} from 'bun:test';
+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
+import {tmpdir} from 'node:os';
+import path from 'node:path';
+import {insertBasicCaptions} from '../codemods/insert-basic-captions';
+import {
+ createFileWatcherRegistry,
+ setFileWatcherRegistry,
+} from '../file-watcher';
+import {setLiveEventsListener} from '../preview-server/live-events';
+import {insertBasicCaptionsHandler} from '../preview-server/routes/insert-basic-captions';
+import {getUndoStack} from '../preview-server/undo-stack';
+import {lineContainingToNodePath} from './test-utils';
+
+test('transcription inserts inline Basic captions beside selected Video and Audio tags', async () => {
+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-captions-'));
+ const entryPoint = path.join(remotionRoot, 'Root.tsx');
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const cleanupLiveEvents = setLiveEventsListener({
+ sendEventToClient: () => undefined,
+ sendEventToClientId: () => true,
+ router: () => Promise.resolve(),
+ closeConnections: () => Promise.resolve(),
+ addNewClientListener: () => () => undefined,
+ });
+ const captions = [
+ {
+ text: ' Hello',
+ startMs: 100,
+ endMs: 400,
+ timestampMs: 250,
+ confidence: null,
+ },
+ ];
+
+ try {
+ (getUndoStack() as unknown as unknown[]).length = 0;
+ writeFileSync(
+ entryPoint,
+ `import {Video, Audio} from '@remotion/media';
+
+export const Comp = () => (
+ <>
+ <Video src="video.mp4" from={10} trimBefore={5} playbackRate={2} />
+ <Audio src="voice.mp3" durationInFrames={60} />
+ </>
+);
+`,
+ );
+
+ for (const [tag, durationInFrames] of [
+ ['<Video', 90],
+ ['<Audio', 60],
+ ] as const) {
+ const current = readFileSync(entryPoint, 'utf-8');
+ const result = await insertBasicCaptionsHandler({
+ input: {
+ fileName: entryPoint,
+ nodePath: lineContainingToNodePath(current, tag),
+ captions,
+ durationInFrames,
+ },
+ entryPoint,
+ remotionRoot,
+ request: {} as never,
+ response: {} as never,
+ logLevel: 'error',
+ methods: {
+ removeJob: () => undefined,
+ cancelJob: () => undefined,
+ addJob: () => undefined,
+ },
+ publicDir: remotionRoot,
+ binariesDirectory: null,
+ configFile: null,
+ getDefaultCodingAgent: () => null,
+ getDefaultEditor: () => null,
+ });
+ expect(result.success).toBe(true);
+ }
+
+ const written = readFileSync(entryPoint, 'utf-8');
+ expect(written).toContain(
+ `import {BasicCaptions} from '@remotion/captions/basic-captions';`,
+ );
+ expect(written.match(/<BasicCaptions/g)).toHaveLength(2);
+ expect(written).toContain('"text": " Hello"');
+ expect(written.replace(/\s+/g, ' ')).toContain(
+ '<BasicCaptions captions={[',
+ );
+ expect(written).toContain('trimBefore={5} playbackRate={2}');
+ expect(written).toContain('durationInFrames={90}');
+ expect(written).toContain('durationInFrames={60}');
+ expect(getUndoStack()).toHaveLength(2);
+ } finally {
+ cleanupFileWatcher();
+ cleanupLiveEvents();
+ rmSync(remotionRoot, {recursive: true, force: true});
+ }
+});
+
+test('wraps a root Audio in a fragment when adding captions', () => {
+ const input = `import {Audio} from 'remotion';
+export const Comp = () => <Audio src="voice.mp3" />;`;
+ const {output} = insertBasicCaptions({
+ input,
+ nodePath: lineContainingToNodePath(input, '<Audio'),
+ captions: [
+ {
+ text: ' Hello',
+ startMs: 0,
+ endMs: 500,
+ timestampMs: null,
+ confidence: null,
+ },
+ ],
+ durationInFrames: 30,
+ });
+
+ expect(output).toContain('<>');
+ expect(output).toContain('<Audio src="voice.mp3" />');
+ expect(output).toContain('<BasicCaptions captions={[');
+ expect(output).toContain('durationInFrames={30}');
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 6c555f373b..9bc8322a30 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -918,6 +918,24 @@ export type SplitVideoFromAudioResponse =
stack: string;
};
+export type InsertBasicCaptionsRequest = {
+ fileName: string;
+ nodePath: SequenceNodePath;
+ durationInFrames: number | null;
+ captions: {
+ text: string;
+ startMs: number;
+ endMs: number;
+ timestampMs: number | null;
+ confidence: number | null;
+ pageBreakAfter?: boolean;
+ }[];
+};
+
+export type InsertBasicCaptionsResponse =
+ | {success: true; nodePathMutation: SequenceNodePathMutation}
+ | {success: false; reason: string; stack: string};
+
export type InsertableCompositionElement =
| {
type: 'solid';
@@ -1412,6 +1430,10 @@ export type ApiRoutes = {
SplitVideoFromAudioRequest,
SplitVideoFromAudioResponse
>;
+ '/api/insert-basic-captions': ReqAndRes<
+ InsertBasicCaptionsRequest,
+ InsertBasicCaptionsResponse
+ >;
'/api/insert-jsx-element': ReqAndRes<
InsertJsxElementRequest,
InsertJsxElementResponse
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index 9f711cde21..6ef1759824 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -60,6 +60,8 @@ import type {
SplitJsxSequenceResponse,
SplitVideoFromAudioRequest,
SplitVideoFromAudioResponse,
+ InsertBasicCaptionsRequest,
+ InsertBasicCaptionsResponse,
SubscribeToDefaultPropsRequest,
SubscribeToDefaultPropsResponse,
SubscribeToSequencePropsRequest,
@@ -222,6 +224,9 @@ export type BrowserStudioOperations = {
splitVideoFromAudio: (
request: SplitVideoFromAudioRequest,
) => Promise<SplitVideoFromAudioResponse>;
+ insertBasicCaptions: (
+ request: InsertBasicCaptionsRequest,
+ ) => Promise<InsertBasicCaptionsResponse>;
subscribeToDefaultProps: (
request: SubscribeToDefaultPropsRequest,
) => Promise<SubscribeToDefaultPropsResponse>;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index d530ddce62..291bfae342 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -73,6 +73,8 @@ export {
GetReleaseNotesResponse,
GoogleFontSourceEdit,
InsertElementFileConflict,
+ InsertBasicCaptionsRequest,
+ InsertBasicCaptionsResponse,
InsertElementRequest,
InsertElementResponse,
InsertJsxElementRequest,
diff --git a/packages/studio/src/components/CurrentAsset.tsx b/packages/studio/src/components/CurrentAsset.tsx
index c51c93ddee..091d2c9fa5 100644
--- a/packages/studio/src/components/CurrentAsset.tsx
+++ b/packages/studio/src/components/CurrentAsset.tsx
@@ -227,6 +227,7 @@ export const AssetInfo: React.FC<{
displayName: fileName,
audioStreamIndex: null,
requestInit: null,
+ target: null,
});
}, [fileName, mutationsDisabled, setSelectedModal, src]);
const onTrackMatting = useCallback(() => {
diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
index fd71e699a1..b9bf037d90 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
@@ -7,7 +7,9 @@ import {AudioIcon} from '../../icons/audio';
import {DuplicateIcon} from '../../icons/duplicate';
import {ScissorsIcon} from '../../icons/scissors';
import {SnowflakeIcon} from '../../icons/snowflake';
+import {TranscriptionIcon} from '../../icons/transcription';
import {TrashIcon} from '../../icons/trash';
+import {SetSelectedModalContext} from '../../state/modals';
import {useConfirmationDialog} from '../ConfirmationDialog';
import {
hasSequenceControls,
@@ -127,6 +129,7 @@ const SequenceSourceQuickActions: React.FC<{
}> = ({selection, track, validatedSource}) => {
const timelinePosition = Internals.Timeline.useTimelinePosition();
const {previewServerState} = useContext(StudioServerConnectionCtx);
+ const {setSelectedModal} = useContext(SetSelectedModalContext);
const {propStatuses} = useContext(Internals.VisualModePropStatusesContext);
const {setPropStatuses} = useContext(Internals.VisualModeSettersContext);
const confirm = useConfirmationDialog();
@@ -154,6 +157,41 @@ const SequenceSourceQuickActions: React.FC<{
});
const sourceActionsDisabled =
previewServerState.type !== 'connected' || !isStudioInteractivityEnabled();
+ const mediaSequence =
+ track.sequence.type === 'video' || track.sequence.type === 'audio'
+ ? track.sequence
+ : null;
+ const transcriptionDisabledReason = sourceActionsDisabled
+ ? 'Studio is read-only'
+ : selection.nodePathInfo.numberOfSequencesWithThisNodePath > 1
+ ? 'Programmatically duplicated media cannot be transcribed from source'
+ : undefined;
+ const onGenerateCaptions = useCallback(() => {
+ if (transcriptionDisabledReason !== undefined || mediaSequence === null) {
+ return;
+ }
+
+ const nodePath = selection.nodePathInfo.sequenceSubscriptionKey;
+ setSelectedModal({
+ type: 'transcribe',
+ src: mediaSequence.src,
+ displayName: mediaSequence.displayName,
+ audioStreamIndex: null,
+ requestInit: null,
+ target: {
+ fileName: nodePath.absolutePath,
+ nodePath,
+ durationInFrames: Number.isFinite(mediaSequence.duration)
+ ? mediaSequence.duration
+ : null,
+ },
+ });
+ }, [
+ selection.nodePathInfo,
+ setSelectedModal,
+ mediaSequence,
+ transcriptionDisabledReason,
+ ]);
const onDuplicate = useCallback(() => {
if (sourceActionsDisabled) {
return;
@@ -222,6 +260,18 @@ const SequenceSourceQuickActions: React.FC<{
Split video from audio
</InspectorQuickAction>
) : null}
+ {track.sequence.type === 'video' || track.sequence.type === 'audio' ? (
+ <InspectorQuickAction
+ disabled={transcriptionDisabledReason !== undefined}
+ onClick={onGenerateCaptions}
+ title={transcriptionDisabledReason}
+ renderIcon={(color) => (
+ <TranscriptionIcon style={actionIconStyle} color={color} />
+ )}
+ >
+ Generate captions
+ </InspectorQuickAction>
+ ) : null}
<InspectorQuickAction
disabled={sourceActionsDisabled}
onClick={onDuplicate}
diff --git a/packages/studio/src/components/RenderQueue/CaptionQueueItem.tsx b/packages/studio/src/components/RenderQueue/CaptionQueueItem.tsx
index 80f60c949e..b085088b7c 100644
--- a/packages/studio/src/components/RenderQueue/CaptionQueueItem.tsx
+++ b/packages/studio/src/components/RenderQueue/CaptionQueueItem.tsx
@@ -124,7 +124,7 @@ export const CaptionQueueItem: React.FC<{
const [hovered, setHovered] = useState(false);
const {removeCaptionJob} = useContext(RenderQueueContext);
const selectAsset = useSelectAsset();
- const isHoverable = job.status === 'done';
+ const isHoverable = job.status === 'done' && job.target === null;
const containerStyle: React.CSSProperties = useMemo(() => {
return {
@@ -157,6 +157,10 @@ export const CaptionQueueItem: React.FC<{
return;
}
+ if (job.target !== null) {
+ return;
+ }
+
selectAsset(job.outName);
pushUrl(`/assets/${job.outName}`);
}, [job, selectAsset]);
@@ -199,7 +203,9 @@ export const CaptionQueueItem: React.FC<{
return job.error.message;
}
- return job.outName;
+ return job.target === null
+ ? job.outName
+ : 'Basic captions added to composition';
}, [job]);
return (
diff --git a/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx b/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx
index 5588dfeeaf..bcca6abd45 100644
--- a/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx
+++ b/packages/studio/src/components/RenderQueue/CaptionQueueProcessor.tsx
@@ -9,6 +9,9 @@ import {
} from '@remotion/whisper-webgpu';
import {useCallback, useContext, useEffect} from 'react';
import {writeStaticFile} from '../../api/write-static-file';
+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
+import {installRequiredPackages} from '../../helpers/install-required-package';
+import {callApi} from '../call-api';
import {resampleMediaTo16Khz} from '../Transcription/resample-media-to-16-khz';
import type {CaptionJob} from './caption-job-types';
import {RenderQueueContext} from './context';
@@ -93,14 +96,38 @@ export const CaptionQueueProcessor: React.FC = () => {
whisperWebGpuOutput: transcription,
});
- updateCaptionJobProgress(job.id, {
- message: `Saving ${job.outName}...`,
- value: 0.95,
- });
- await writeStaticFile({
- contents: JSON.stringify(captions, null, 2),
- filePath: job.outName,
- });
+ if (job.target === null) {
+ updateCaptionJobProgress(job.id, {
+ message: `Saving ${job.outName}...`,
+ value: 0.95,
+ });
+ await writeStaticFile({
+ contents: JSON.stringify(captions, null, 2),
+ filePath: job.outName,
+ });
+ } else {
+ updateCaptionJobProgress(job.id, {
+ message: 'Adding Basic captions...',
+ value: 0.95,
+ });
+ await installRequiredPackages([
+ {name: '@remotion/captions', version: null},
+ ]);
+ const request = {
+ fileName: job.target.fileName,
+ nodePath: job.target.nodePath.nodePath,
+ durationInFrames: job.target.durationInFrames,
+ captions,
+ };
+ const browserStudioOperations = getBrowserStudioOperations();
+ const response = browserStudioOperations
+ ? await browserStudioOperations.insertBasicCaptions(request)
+ : await callApi('/api/insert-basic-captions', request);
+ if (!response.success) {
+ throw new Error(response.reason);
+ }
+ }
+
captionCount = captions.length;
} catch (error) {
processingError =
diff --git a/packages/studio/src/components/RenderQueue/caption-job-types.ts b/packages/studio/src/components/RenderQueue/caption-job-types.ts
index 37d5fad37a..41868e7dce 100644
--- a/packages/studio/src/components/RenderQueue/caption-job-types.ts
+++ b/packages/studio/src/components/RenderQueue/caption-job-types.ts
@@ -2,6 +2,7 @@ import type {
WhisperWebGpuModel,
WhisperWebGpuTask,
} from '@remotion/whisper-webgpu';
+import type {SequencePropsSubscriptionKey} from 'remotion';
export type CaptionJobProgress = {
message: string;
@@ -23,6 +24,11 @@ export type AddCaptionJobParams = {
audioStreamIndex: number | null;
requestInit: Omit<RequestInit, 'signal'> | null;
outName: string;
+ target: {
+ fileName: string;
+ nodePath: SequencePropsSubscriptionKey;
+ durationInFrames: number | null;
+ } | null;
model: WhisperWebGpuModel;
language: string | null;
task: WhisperWebGpuTask;
diff --git a/packages/studio/src/components/RenderQueue/index.tsx b/packages/studio/src/components/RenderQueue/index.tsx
index ae10ab843e..05caeae03a 100644
--- a/packages/studio/src/components/RenderQueue/index.tsx
+++ b/packages/studio/src/components/RenderQueue/index.tsx
@@ -90,6 +90,7 @@ export const RenderQueue: React.FC = () => {
const job = allJobs[i];
if (
isCaptionJob(job) &&
+ job.target === null &&
job.status === 'done' &&
canvasContent.asset === job.outName
) {
diff --git a/packages/studio/src/components/Transcription/TranscriptionModal.tsx b/packages/studio/src/components/Transcription/TranscriptionModal.tsx
index 9d8b7ac308..20efae0cf7 100644
--- a/packages/studio/src/components/Transcription/TranscriptionModal.tsx
+++ b/packages/studio/src/components/Transcription/TranscriptionModal.tsx
@@ -705,6 +705,7 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
displayName,
requestInit,
src,
+ target,
}) => {
const [tab, setTab] = useState<Tab>('transcribe');
const isModelCached = useCallback(
@@ -771,14 +772,17 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
const normalizedOutName = outName.normalize('NFC').toLowerCase();
const queuedOutputExists = captionJobs.some(
(job) =>
+ job.target === null &&
(job.status === 'idle' || job.status === 'running') &&
job.outName.normalize('NFC').toLowerCase() === normalizedOutName,
);
const outputValidationMessage =
- validateCaptionOutputName(outName) ??
- (queuedOutputExists
- ? 'Another caption job is already using this output file'
- : null);
+ target === null
+ ? (validateCaptionOutputName(outName) ??
+ (queuedOutputExists
+ ? 'Another caption job is already using this output file'
+ : null))
+ : null;
const exists = staticFiles.some(
(file) => file.name.normalize('NFC').toLowerCase() === normalizedOutName,
);
@@ -836,7 +840,8 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
displayName,
audioStreamIndex,
requestInit,
- outName,
+ outName: target === null ? outName : 'Basic captions',
+ target,
model: selectedModel,
language: modelInfo.multilingual ? selectedLanguage : null,
task: modelInfo.supportsTranslation ? selectedTask : 'transcribe',
@@ -863,6 +868,7 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
forceFullSequences,
noRepeatNgramSize,
outName,
+ target,
repetitionPenalty,
requestInit,
src,
@@ -876,10 +882,13 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
topK,
]);
+ const title =
+ target === null ? `Transcribe ${displayName}` : 'Generate captions';
+
return (
- <DismissableModal ariaLabel={`Transcribe ${displayName}`}>
+ <DismissableModal ariaLabel={title}>
<div style={transcriptionModalStyle}>
- <ModalHeader title={`Transcribe ${displayName}`} />
+ <ModalHeader title={title} />
<div style={container}>
<div style={flexer} />
<Button
@@ -893,7 +902,7 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
: BLUE_DISABLED,
}}
>
- Transcribe
+ {target === null ? 'Transcribe' : 'Generate captions'}
</Button>
</div>
<div style={transcriptionLayout}>
@@ -909,7 +918,7 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
</div>
)}
>
- Transcribe
+ {target === null ? 'Transcribe' : 'Generate captions'}
</VerticalTab>
<VerticalTab
style={horizontalTab}
@@ -940,13 +949,15 @@ export const TranscriptionModal: React.FC<TranscriptionModalState> = ({
style={tab === 'transcribe' ? settingsPanel : hiddenPanel}
className={VERTICAL_SCROLLBAR_CLASSNAME}
>
- <OutputSettings
- exists={exists}
- onOutNameChange={onOutNameChange}
- outName={outName}
- validationMessage={outputValidationMessage}
- />
- <RenderModalHr />
+ {target === null ? (
+ <OutputSettings
+ exists={exists}
+ onOutNameChange={onOutNameChange}
+ outName={outName}
+ validationMessage={outputValidationMessage}
+ />
+ ) : null}
+ {target === null ? <RenderModalHr /> : null}
<ModelSettings
cachedModels={cachedModels}
selectedLanguage={selectedLanguage}
diff --git a/packages/studio/src/components/Transcription/TranscriptionModalWithOptionalWhisper.tsx b/packages/studio/src/components/Transcription/TranscriptionModalWithOptionalWhisper.tsx
index b035bdcbb7..6bb9245b98 100644
--- a/packages/studio/src/components/Transcription/TranscriptionModalWithOptionalWhisper.tsx
+++ b/packages/studio/src/components/Transcription/TranscriptionModalWithOptionalWhisper.tsx
@@ -15,7 +15,7 @@ export const TranscriptionModalWithOptionalWhisper: React.FC<{
<OptionalPackageModal
ariaLabel="Install transcription package"
packageName={WHISPER_WEBGPU_PACKAGE}
- title="Transcribe"
+ title={state.target === null ? 'Transcribe' : 'Generate captions'}
>
<Suspense fallback={null}>
<LazyTranscriptionModal {...state} />
diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsx
index 903413e9c6..7b1da56d9e 100644
--- a/packages/studio/src/components/WebMcp.tsx
+++ b/packages/studio/src/components/WebMcp.tsx
@@ -618,6 +618,7 @@ export const WebMcp: FC = () => {
model: model.name,
noRepeatNgramSize,
outName: outputPath,
+ target: null,
repetitionPenalty,
requestInit: null,
src,
diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.ts
index b33f0566ef..842b9915c6 100644
--- a/packages/studio/src/state/modals.ts
+++ b/packages/studio/src/state/modals.ts
@@ -159,6 +159,11 @@ export type TranscriptionModalState = {
displayName: string;
audioStreamIndex: number | null;
requestInit: Omit<RequestInit, 'signal'> | null;
+ target: {
+ fileName: string;
+ nodePath: SequencePropsSubscriptionKey;
+ durationInFrames: number | null;
+ } | null;
};
export type VideoMattingModalState = {
diff --git a/packages/studio/src/test/caption-queue-processor.test.tsx b/packages/studio/src/test/caption-queue-processor.test.tsx
index 6355230998..e102045789 100644
--- a/packages/studio/src/test/caption-queue-processor.test.tsx
+++ b/packages/studio/src/test/caption-queue-processor.test.tsx
@@ -188,6 +188,8 @@ test('downloads a model in the queued job before transcribing', async () => {
window,
'remotion_browserStudio',
);
+ const originalInstalledPackages = window.remotion_installedPackages;
+ const originalFetch = globalThis.fetch;
const writtenFiles: Array<{
contents: string | ArrayBuffer;
filePath: string;
@@ -252,6 +254,7 @@ test('downloads a model in the queued job before transcribing', async () => {
repetitionPenalty: 1.2,
noRepeatNgramSize: 3,
outName: 'captions/interview.json',
+ target: null,
src: '/static/interview.wav',
});
});
@@ -346,7 +349,152 @@ test('downloads a model in the queued job before transcribing', async () => {
},
]);
expect(disposalCalls).toBe(1);
+
+ const insertedRequests: Array<{endpoint: string; body: unknown}> = [];
+ window.remotion_installedPackages = ['@remotion/captions'];
+ Object.defineProperty(window, 'remotion_browserStudio', {
+ configurable: true,
+ value: null,
+ });
+ globalThis.fetch = ((endpoint: string, init: RequestInit) => {
+ insertedRequests.push({
+ endpoint,
+ body: JSON.parse(String(init.body)),
+ });
+ return Promise.resolve({
+ json: () =>
+ Promise.resolve({
+ success: true,
+ data: {success: true, nodePathMutation: null},
+ }),
+ }) as Promise<Response>;
+ }) as typeof fetch;
+ modelLoadCall = undefined;
+ let inlineJobId = '';
+ act(() => {
+ inlineJobId = getContext().addCaptionJob({
+ displayName: 'clip.mp4',
+ audioStreamIndex: null,
+ requestInit: null,
+ language: null,
+ model: 'tiny',
+ chunkLengthInSeconds: 30,
+ strideLengthInSeconds: 5,
+ task: 'transcribe',
+ forceFullSequences: false,
+ doSample: false,
+ temperature: 1,
+ topK: 50,
+ repetitionPenalty: 1,
+ noRepeatNgramSize: 0,
+ outName: 'Basic captions',
+ target: {
+ fileName: '/project/Root.tsx',
+ nodePath: {
+ absolutePath: '/project/Root.tsx',
+ nodePath: [0],
+ sequenceKeys: [],
+ effectKeys: [],
+ videoConfigValues: null,
+ },
+ durationInFrames: 90,
+ },
+ src: '/static/clip.mp4',
+ });
+ });
+ await waitFor(() => expect(modelLoadCall).toBeDefined());
+ act(() => resolveModelLoading?.());
+ await waitFor(() => {
+ expect(
+ getContext().captionJobs.find((job) => job.id === inlineJobId),
+ ).toMatchObject({status: 'done', captionCount: 2});
+ });
+ expect(insertedRequests).toEqual([
+ {
+ endpoint: '/api/insert-basic-captions',
+ body: {
+ fileName: '/project/Root.tsx',
+ nodePath: [0],
+ durationInFrames: 90,
+ captions: [
+ {
+ text: 'Hello',
+ startMs: 125,
+ endMs: 625,
+ timestampMs: 375,
+ confidence: null,
+ },
+ {
+ text: ' world.',
+ startMs: 750,
+ endMs: 1500,
+ timestampMs: 1125,
+ confidence: null,
+ },
+ ],
+ },
+ },
+ ]);
+ expect(writtenFiles).toHaveLength(1);
+
+ const browserRequests: unknown[] = [];
+ Object.defineProperty(window, 'remotion_browserStudio', {
+ configurable: true,
+ value: makeBrowserStudioOperations({
+ insertBasicCaptions: (request) => {
+ browserRequests.push(request);
+ return Promise.resolve({
+ success: true,
+ nodePathMutation: {
+ mutationId: 'captions-browser',
+ timelineSelection: null,
+ files: [],
+ },
+ });
+ },
+ }),
+ });
+ const previousJob = getContext().captionJobs.find(
+ (job) => job.id === inlineJobId,
+ );
+ if (!previousJob || previousJob.target === null) {
+ throw new Error('Inline captions job is missing');
+ }
+
+ const previousTarget = previousJob.target;
+
+ modelLoadCall = undefined;
+ let browserJobId = '';
+ act(() => {
+ browserJobId = getContext().addCaptionJob({
+ ...previousJob,
+ src: '/static/browser-clip.mp4',
+ target: {
+ ...previousTarget,
+ fileName: '/project/Browser.tsx',
+ durationInFrames: 45,
+ },
+ });
+ });
+ await waitFor(() => expect(modelLoadCall).toBeDefined());
+ act(() => resolveModelLoading?.());
+ await waitFor(() => {
+ expect(
+ getContext().captionJobs.find((job) => job.id === browserJobId),
+ ).toMatchObject({status: 'done', captionCount: 2});
+ });
+ expect(browserRequests).toEqual([
+ {
+ fileName: '/project/Browser.tsx',
+ nodePath: [0],
+ durationInFrames: 45,
+ captions: (insertedRequests[0].body as {captions: unknown}).captions,
+ },
+ ]);
+ expect(insertedRequests).toHaveLength(1);
} finally {
+ globalThis.fetch = originalFetch;
+ window.remotion_installedPackages = originalInstalledPackages;
if (originalGpuDescriptor) {
Object.defineProperty(navigator, 'gpu', originalGpuDescriptor);
} else {
diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.ts
index ea974c242d..16af2c2bd1 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -53,6 +53,7 @@ export const makeBrowserStudioOperations = (
saveSequenceProps: () => unusedOperation('saveSequenceProps'),
splitJsxSequence: () => unusedOperation('splitJsxSequence'),
splitVideoFromAudio: () => unusedOperation('splitVideoFromAudio'),
+ insertBasicCaptions: () => unusedOperation('insertBasicCaptions'),
subscribeToDefaultProps: () => unusedOperation('subscribeToDefaultProps'),
subscribeToEvent: () => unusedOperation('subscribeToEvent'),
subscribeToSequenceProps: () => unusedOperation('subscribeToSequenceProps'),
diff --git a/packages/studio/src/test/render-queue-scheduler.test.tsx b/packages/studio/src/test/render-queue-scheduler.test.tsx
index cbf663274d..9fe2c713f5 100644
--- a/packages/studio/src/test/render-queue-scheduler.test.tsx
+++ b/packages/studio/src/test/render-queue-scheduler.test.tsx
@@ -30,6 +30,7 @@ const makeCaptionParams = (displayName: string): AddCaptionJobParams => ({
audioStreamIndex: null,
requestInit: null,
outName: `${displayName}.json`,
+ target: null,
model: 'tiny.en',
language: null,
chunkLengthInSeconds: 30,
diff --git a/packages/studio/src/test/renders-tab-caption-jobs.test.tsx b/packages/studio/src/test/renders-tab-caption-jobs.test.tsx
index 6afc64f8c7..1f1dfcb9c7 100644
--- a/packages/studio/src/test/renders-tab-caption-jobs.test.tsx
+++ b/packages/studio/src/test/renders-tab-caption-jobs.test.tsx
@@ -54,6 +54,7 @@ const baseJob = {
audioStreamIndex: null,
requestInit: null,
outName: 'dialogue-captions.json',
+ target: null,
model: 'tiny.en',
language: null,
chunkLengthInSeconds: 30,
diff --git a/packages/studio/src/test/transcription-modal.test.tsx b/packages/studio/src/test/transcription-modal.test.tsx
index 4e36233cd9..3be7724c06 100644
--- a/packages/studio/src/test/transcription-modal.test.tsx
+++ b/packages/studio/src/test/transcription-modal.test.tsx
@@ -144,6 +144,7 @@ test('serializes transcription modal settings into caption jobs', async () => {
displayName="interview.wav"
requestInit={requestInit}
src="/media/interview.wav"
+ target={null}
/>
</StaticFilesProvider>
</RenderQueueContext.Provider>
@@ -267,6 +268,7 @@ test('serializes transcription modal settings into caption jobs', async () => {
model: 'tiny',
noRepeatNgramSize: 3,
outName: 'captions/interview.json',
+ target: null,
repetitionPenalty: 1.2,
requestInit,
src: '/media/interview.wav',
diff --git a/packages/studio/src/test/whisper-webgpu-capability.test.tsx b/packages/studio/src/test/whisper-webgpu-capability.test.tsx
index 753a92eeb4..4b26f9fbe9 100644
--- a/packages/studio/src/test/whisper-webgpu-capability.test.tsx
+++ b/packages/studio/src/test/whisper-webgpu-capability.test.tsx
@@ -49,6 +49,7 @@ test('asks before installing Whisper for transcription', () => {
displayName: 'voice.wav',
audioStreamIndex: null,
requestInit: null,
+ target: null,
}}
/>
</ModalsProvider>,
@@ -105,6 +106,7 @@ test('opens transcription after installing Whisper without restarting', async ()
displayName: 'voice.wav',
audioStreamIndex: null,
requestInit: null,
+ target: null,
}}
/>
</ModalsProvider>,