Skip to content

🎥 Make videos programmatically with React

`remotion`: Add captions interactivity schema field (#9715)

Igor Samokhovetsa4c4ea3cbfbc
diff --git a/bun.lock b/bun.lock
index 57a9352f11..8bccb89ceb 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1658,6 +1658,7 @@
"dependencies": {
"@jridgewell/trace-mapping": "0.3.31",
"@remotion/canvas-capture": "workspace:*",
+ "@remotion/captions": "workspace:*",
"@remotion/drag-and-drop": "workspace:*",
"@remotion/media-utils": "workspace:*",
"@remotion/player": "workspace:*",
diff --git a/packages/core/src/Interactive.tsx b/packages/core/src/Interactive.tsx
index 86356a584e..39077394d8 100644
--- a/packages/core/src/Interactive.tsx
+++ b/packages/core/src/Interactive.tsx
@@ -7,6 +7,7 @@ import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
import {
backgroundSchema,
baseSchema,
+ captionsSchema,
borderSchema,
cropSchema,
premountSchema,
@@ -317,6 +318,7 @@ const makeInteractiveSvgStrokeElement = <Tag extends InteractiveSvgTag>(
*/
export const Interactive = {
baseSchema,
+ captionsSchema,
transformSchema,
textSchema,
backgroundSchema,
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index b750eadd19..7863f7fa30 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -23,6 +23,7 @@ import type {
AssetFieldSchema,
ArrayFieldSchema,
ArrayItemFieldSchema,
+ CaptionsFieldSchema,
InteractivitySchemaField,
InteractivitySchema,
} from './interactivity-schema.js';
@@ -343,6 +344,7 @@ export type {
AssetFieldSchema,
ArrayFieldSchema,
ArrayItemFieldSchema,
+ CaptionsFieldSchema,
DelayRenderScope,
JsxComponentIdentity,
LoopDisplay,
diff --git a/packages/core/src/interactivity-schema.ts b/packages/core/src/interactivity-schema.ts
index ef8403532a..7ba380fd43 100644
--- a/packages/core/src/interactivity-schema.ts
+++ b/packages/core/src/interactivity-schema.ts
@@ -192,6 +192,13 @@ export type ArrayFieldSchema = {
keyframable?: false;
};
+export type CaptionsFieldSchema = {
+ type: 'remotion-captions';
+ default: readonly unknown[] | undefined;
+ description?: string;
+ keyframable: false;
+};
+
export type VisibleFieldSchema =
| NumberFieldSchema
| BooleanFieldSchema
@@ -206,12 +213,22 @@ export type VisibleFieldSchema =
| FontFamilyFieldSchema
| AssetFieldSchema
| ArrayFieldSchema
+ | CaptionsFieldSchema
| EnumFieldSchema;
export type InteractivitySchemaField = VisibleFieldSchema | HiddenFieldSchema;
export type InteractivitySchema = {[key: string]: InteractivitySchemaField};
+export const captionsSchema = {
+ captions: {
+ type: 'remotion-captions',
+ default: undefined,
+ description: 'Captions',
+ keyframable: false,
+ },
+} as const satisfies InteractivitySchema;
+
export type InteractivitySchemaKeysRecord<S extends InteractivitySchema> =
Record<keyof S, unknown>;
diff --git a/packages/core/src/test/with-interactivity-schema-helpers.test.ts b/packages/core/src/test/with-interactivity-schema-helpers.test.ts
index 2e15b91114..8839275298 100644
--- a/packages/core/src/test/with-interactivity-schema-helpers.test.ts
+++ b/packages/core/src/test/with-interactivity-schema-helpers.test.ts
@@ -15,6 +15,7 @@ import {
backgroundSchema,
baseSchema,
borderSchema,
+ captionsSchema,
cropSchema,
extendSchemaWithSequenceName,
premountSchema,
@@ -103,6 +104,18 @@ test('cropSchema is reusable and supported components opt into it', () => {
expect('cropLeft' in baseSchema).toBe(false);
});
+test('captionsSchema is reusable', () => {
+ expect(Interactive.captionsSchema).toBe(captionsSchema);
+ expect(captionsSchema).toEqual({
+ captions: {
+ type: 'remotion-captions',
+ default: undefined,
+ description: 'Captions',
+ keyframable: false,
+ },
+ });
+});
+
test('baseSchema exposes common timeline fields', () => {
expect(Object.keys(baseSchema).sort()).toEqual(
[
diff --git a/packages/docs/docs/interactivity-schema.mdx b/packages/docs/docs/interactivity-schema.mdx
index d47ad73040..42295da2b1 100644
--- a/packages/docs/docs/interactivity-schema.mdx
+++ b/packages/docs/docs/interactivity-schema.mdx
@@ -39,6 +39,12 @@ Keys may use dot notation. For example, a key named `style.opacity` reads from a
Timeline props inherited from [`<Sequence>`](/docs/sequence): [`durationInFrames`](/docs/sequence#durationinframes), [`from`](/docs/sequence#from), [`trimBefore`](/docs/sequence#trimbefore), [`freeze`](/docs/sequence#freeze), [`hidden`](/docs/sequence#hidden), [`name`](/docs/sequence#name) and [`showInTimeline`](/docs/sequence#showintimeline).
+### `Interactive.captionsSchema`<AvailableFrom v="4.0.500" />
+
+A `captions` field for components that accept [`Caption[]`](/docs/captions/caption) data. It enables the captions inspector and is not keyframable.
+
+This schema fragment is headless: it does not render an element or add layout, transform, or text-style controls. Add other `Interactive` schema fragments only when the component renders and supports those props.
+
### `Interactive.transformSchema`
Transform-related style props: `style.transformOrigin`, `style.translate`, `style.scale`, `style.rotate` and `style.opacity`.
@@ -101,6 +107,10 @@ Shows a select control. Each variant can define its own nested `InteractivitySch
Shows a list of values. Array fields are not keyframable.
+### `remotion-captions`<AvailableFrom v="4.0.500" />
+
+Marks a prop containing [`Caption[]`](/docs/captions/caption) data for the captions inspector. Caption fields are not keyframable.
+
### `rotation-css`
Shows a rotation control backed by a CSS rotation string such as `"15deg"`.
diff --git a/packages/docs/docs/studio/make-component-interactive.mdx b/packages/docs/docs/studio/make-component-interactive.mdx
index 99734d4b96..f235c42936 100644
--- a/packages/docs/docs/studio/make-component-interactive.mdx
+++ b/packages/docs/docs/studio/make-component-interactive.mdx
@@ -56,6 +56,21 @@ const badgeSchema = {
} as const satisfies InteractivitySchema;
```
+## Caption fields<AvailableFrom v="4.0.500" />
+
+Add a `captions` field when a custom component accepts [`Caption[]`](/docs/captions/caption) data:
+
+```ts twoslash title="Captions.tsx"
+import {Interactive, type InteractivitySchema} from 'remotion';
+
+const captionsSchema = {
+ ...Interactive.baseSchema,
+ ...Interactive.captionsSchema,
+} as const satisfies InteractivitySchema;
+```
+
+Studio can edit caption text when the prop is a direct JSX array literal, such as `captions={[...]}`. Variables, imports, computed expressions, and `satisfies` expressions are read-only.
+
## Forward `controls` and `stack`
The inner component receives `controls` and `stack` props from `Interactive.withSchema()`.
diff --git a/packages/example/src/CaptionsTester/AnimatedCaptions.tsx b/packages/example/src/CaptionsTester/AnimatedCaptions.tsx
index d5a612fee6..d8ab890953 100644
--- a/packages/example/src/CaptionsTester/AnimatedCaptions.tsx
+++ b/packages/example/src/CaptionsTester/AnimatedCaptions.tsx
@@ -1,24 +1,49 @@
import type {Caption, TikTokPage} from '@remotion/captions';
import {createTikTokStyleCaptions} from '@remotion/captions';
-import React, {useCallback, useEffect, useMemo, useState} from 'react';
+import React, {forwardRef, useImperativeHandle, useMemo, useRef} from 'react';
import {
AbsoluteFill,
+ Interactive,
interpolate,
Sequence,
spring,
- staticFile,
+ type InteractiveBaseProps,
+ type InteractiveTransformProps,
+ type InteractivitySchema,
+ type SequenceControls,
+ type SequenceProps,
useCurrentFrame,
- useDelayRender,
useVideoConfig,
} from 'remotion';
-export const CAPTIONS_FILE = 'voiceover-captions.json';
export const CAPTIONS_DURATION_IN_FRAMES = 1628;
export const CAPTIONS_HEIGHT = 360;
const SWITCH_CAPTIONS_EVERY_MS = 1100;
const HIGHLIGHT_COLOR = '#6cf6ff';
+const animatedCaptionsSchema = {
+ ...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,
+ },
+ ...Interactive.transformSchema,
+} as const satisfies InteractivitySchema;
+
const CaptionPage: React.FC<{page: TikTokPage}> = ({page}) => {
const frame = useCurrentFrame();
const {fps} = useVideoConfig();
@@ -88,47 +113,36 @@ const CaptionPage: React.FC<{page: TikTokPage}> = ({page}) => {
);
};
-export const AnimatedCaptions: React.FC = () => {
- const [captions, setCaptions] = useState<Caption[] | null>(null);
- const {delayRender, continueRender, cancelRender} = useDelayRender();
- const [handle] = useState(() => delayRender('Loading ElevenLabs captions'));
- const {fps} = useVideoConfig();
-
- const loadCaptions = useCallback(async () => {
- try {
- const response = await fetch(staticFile(CAPTIONS_FILE));
- if (!response.ok) {
- throw new Error(`Could not load captions (${response.status})`);
- }
-
- setCaptions((await response.json()) as Caption[]);
- continueRender(handle);
- } catch (error) {
- cancelRender(error);
- }
- }, [cancelRender, continueRender, handle]);
-
- useEffect(() => {
- loadCaptions();
- }, [loadCaptions]);
+type AnimatedCaptionsProps = InteractiveBaseProps &
+ InteractiveTransformProps &
+ Pick<SequenceProps, 'width' | 'height'> & {
+ readonly captions: Caption[];
+ };
+const AnimatedCaptionsInner = forwardRef<
+ HTMLDivElement,
+ AnimatedCaptionsProps & {readonly controls: SequenceControls | undefined}
+>(({captions, controls, name, style, ...sequenceProps}, ref) => {
+ const outlineRef = useRef<HTMLDivElement>(null);
+ const {fps} = useVideoConfig();
const pages = useMemo(() => {
- if (!captions) {
- return [];
- }
-
return createTikTokStyleCaptions({
captions,
combineTokensWithinMilliseconds: SWITCH_CAPTIONS_EVERY_MS,
}).pages;
}, [captions]);
- if (!captions) {
- return null;
- }
+ useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);
return (
- <AbsoluteFill>
+ <Sequence
+ ref={outlineRef}
+ {...sequenceProps}
+ name={name ?? '<AnimatedCaptions>'}
+ style={style}
+ controls={controls}
+ outlineRef={outlineRef}
+ >
{pages.map((page, index) => {
const nextPage = pages[index + 1];
const startFrame = Math.round((page.startMs / 1000) * fps);
@@ -149,11 +163,20 @@ export const AnimatedCaptions: React.FC = () => {
from={startFrame}
durationInFrames={durationInFrames}
premountFor={fps}
+ showInTimeline={false}
>
<CaptionPage page={page} />
</Sequence>
);
})}
- </AbsoluteFill>
+ </Sequence>
);
-};
+});
+
+export const AnimatedCaptions = Interactive.withSchema({
+ Component: AnimatedCaptionsInner,
+ componentName: '<AnimatedCaptions>',
+ componentIdentity: null,
+ schema: animatedCaptionsSchema,
+ supportsEffects: false,
+});
diff --git a/packages/example/src/CaptionsTester/AnimatedCaptionsComposition.tsx b/packages/example/src/CaptionsTester/AnimatedCaptionsComposition.tsx
new file mode 100644
index 0000000000..c2e115cca5
--- /dev/null
+++ b/packages/example/src/CaptionsTester/AnimatedCaptionsComposition.tsx
@@ -0,0 +1,6 @@
+import React from 'react';
+import {InlineAnimatedCaptions} from './InlineAnimatedCaptions';
+
+export const AnimatedCaptionsComposition: React.FC = () => {
+ return <InlineAnimatedCaptions />;
+};
diff --git a/packages/example/src/CaptionsTester/InlineAnimatedCaptions.tsx b/packages/example/src/CaptionsTester/InlineAnimatedCaptions.tsx
new file mode 100644
index 0000000000..7d88abf0ab
--- /dev/null
+++ b/packages/example/src/CaptionsTester/InlineAnimatedCaptions.tsx
@@ -0,0 +1,1239 @@
+import React from 'react';
+import {AnimatedCaptions} from './AnimatedCaptions';
+
+export const InlineAnimatedCaptions: React.FC = () => {
+ return (
+ <AnimatedCaptions
+ height={260}
+ style={{translate: '90px 50px'}}
+ width={900}
+ captions={[
+ {
+ confidence: null,
+ startMs: 99,
+ endMs: 199,
+ text: 'I',
+ timestampMs: 149,
+ },
+ {
+ confidence: null,
+ startMs: 199,
+ endMs: 459,
+ text: ' vibe',
+ timestampMs: 329,
+ },
+ {
+ confidence: null,
+ startMs: 459,
+ endMs: 799,
+ text: ' coded',
+ timestampMs: 629,
+ },
+ {
+ confidence: null,
+ startMs: 799,
+ endMs: 1079,
+ text: ' my',
+ timestampMs: 939,
+ },
+ {
+ confidence: null,
+ startMs: 1079,
+ endMs: 1279,
+ text: ' own',
+ timestampMs: 1179,
+ },
+ {
+ confidence: null,
+ startMs: 1279,
+ endMs: 1620,
+ text: ' DJ',
+ timestampMs: 1449.5,
+ },
+ {
+ confidence: null,
+ startMs: 1620,
+ endMs: 1839,
+ text: ' show',
+ timestampMs: 1729.5,
+ },
+ {
+ confidence: null,
+ startMs: 1839,
+ endMs: 2039.0000000000002,
+ text: ' by',
+ timestampMs: 1939,
+ },
+ {
+ confidence: null,
+ startMs: 2039.0000000000002,
+ endMs: 2539,
+ text: ' programming',
+ timestampMs: 2289,
+ },
+ {
+ confidence: null,
+ startMs: 2539,
+ endMs: 2819,
+ text: ' lights',
+ timestampMs: 2679,
+ },
+ {
+ confidence: null,
+ startMs: 2819,
+ endMs: 2960,
+ text: ' with',
+ timestampMs: 2889.5,
+ },
+ {
+ confidence: null,
+ startMs: 2960,
+ endMs: 3279,
+ text: ' AI',
+ timestampMs: 3119.5,
+ },
+ {
+ confidence: null,
+ startMs: 3279,
+ endMs: 3740,
+ text: ' agents',
+ timestampMs: 3509.5,
+ },
+ {
+ confidence: null,
+ startMs: 3740,
+ endMs: 3919,
+ text: ' and',
+ timestampMs: 3829.5,
+ },
+ {
+ confidence: null,
+ startMs: 3919,
+ endMs: 4279,
+ text: ' making',
+ timestampMs: 4099,
+ },
+ {
+ confidence: null,
+ startMs: 4279,
+ endMs: 4699,
+ text: ' visuals',
+ timestampMs: 4489,
+ },
+ {
+ confidence: null,
+ startMs: 4699,
+ endMs: 4839,
+ text: ' with',
+ timestampMs: 4769,
+ },
+ {
+ confidence: null,
+ startMs: 4839,
+ endMs: 5033.333333333333,
+ text: ' Remotion,',
+ timestampMs: 4936.166667,
+ },
+ {
+ confidence: null,
+ startMs: 5440,
+ endMs: 5960,
+ text: ' and',
+ timestampMs: 5700,
+ },
+ {
+ confidence: null,
+ startMs: 5960,
+ endMs: 6039,
+ text: ' I',
+ timestampMs: 5999.5,
+ },
+ {
+ confidence: null,
+ startMs: 6039,
+ endMs: 6159,
+ text: ' am',
+ timestampMs: 6099,
+ },
+ {
+ confidence: null,
+ startMs: 6159,
+ endMs: 6440,
+ text: ' showing',
+ timestampMs: 6299.5,
+ },
+ {
+ confidence: null,
+ startMs: 6440,
+ endMs: 6619,
+ text: ' you',
+ timestampMs: 6529.5,
+ },
+ {
+ confidence: null,
+ startMs: 6619,
+ endMs: 6779,
+ text: ' how',
+ timestampMs: 6699,
+ },
+ {
+ confidence: null,
+ startMs: 6779,
+ endMs: 6899,
+ text: ' you',
+ timestampMs: 6839,
+ },
+ {
+ confidence: null,
+ startMs: 6899,
+ endMs: 7039,
+ text: ' can',
+ timestampMs: 6969,
+ },
+ {
+ confidence: null,
+ startMs: 7039,
+ endMs: 7139,
+ text: ' do',
+ timestampMs: 7089,
+ },
+ {
+ confidence: null,
+ startMs: 7139,
+ endMs: 7279,
+ text: ' it',
+ timestampMs: 7209,
+ },
+ {
+ confidence: null,
+ startMs: 7279,
+ endMs: 7460,
+ text: ' as',
+ timestampMs: 7369.5,
+ },
+ {
+ confidence: null,
+ startMs: 7460,
+ endMs: 7699,
+ text: ' well.',
+ timestampMs: 7579.5,
+ },
+ {
+ confidence: null,
+ startMs: 7699,
+ endMs: 7919,
+ text: ' For',
+ timestampMs: 7809,
+ },
+ {
+ confidence: null,
+ startMs: 7919,
+ endMs: 8099,
+ text: ' this',
+ timestampMs: 8009,
+ },
+ {
+ confidence: null,
+ startMs: 8099,
+ endMs: 8380,
+ text: ' track,',
+ timestampMs: 8239.5,
+ },
+ {
+ confidence: null,
+ startMs: 8380,
+ endMs: 8519,
+ text: ' I',
+ timestampMs: 8449.5,
+ },
+ {
+ confidence: null,
+ startMs: 8519,
+ endMs: 8659,
+ text: ' took',
+ timestampMs: 8589,
+ },
+ {
+ confidence: null,
+ startMs: 8659,
+ endMs: 8760,
+ text: ' the',
+ timestampMs: 8709.5,
+ },
+ {
+ confidence: null,
+ startMs: 8760,
+ endMs: 9059,
+ text: ' music',
+ timestampMs: 8909.5,
+ },
+ {
+ confidence: null,
+ startMs: 9059,
+ endMs: 9380,
+ text: ' video',
+ timestampMs: 9219.5,
+ },
+ {
+ confidence: null,
+ startMs: 9380,
+ endMs: 9560,
+ text: ' and',
+ timestampMs: 9470,
+ },
+ {
+ confidence: null,
+ startMs: 9560,
+ endMs: 10139,
+ text: ' inserted',
+ timestampMs: 9849.5,
+ },
+ {
+ confidence: null,
+ startMs: 10139,
+ endMs: 10659,
+ text: ' animated',
+ timestampMs: 10399,
+ },
+ {
+ confidence: null,
+ startMs: 10659,
+ endMs: 11199,
+ text: ' captions',
+ timestampMs: 10929,
+ },
+ {
+ confidence: null,
+ startMs: 11199,
+ endMs: 11340,
+ text: ' in',
+ timestampMs: 11269.5,
+ },
+ {
+ confidence: null,
+ startMs: 11340,
+ endMs: 11699,
+ text: ' between',
+ timestampMs: 11519.5,
+ },
+ {
+ confidence: null,
+ startMs: 11699,
+ endMs: 11779,
+ text: ' the',
+ timestampMs: 11739,
+ },
+ {
+ confidence: null,
+ startMs: 11779,
+ endMs: 12399,
+ text: ' foreground',
+ timestampMs: 12089,
+ },
+ {
+ confidence: null,
+ startMs: 12399,
+ endMs: 12579,
+ text: ' and',
+ timestampMs: 12489,
+ },
+ {
+ confidence: null,
+ startMs: 12579,
+ endMs: 12699,
+ text: ' the',
+ timestampMs: 12639,
+ },
+ {
+ confidence: null,
+ startMs: 12699,
+ endMs: 13439,
+ text: ' background.',
+ timestampMs: 13069,
+ },
+ {
+ confidence: null,
+ startMs: 13439,
+ endMs: 14019,
+ text: ' How',
+ timestampMs: 13729,
+ },
+ {
+ confidence: null,
+ startMs: 14019,
+ endMs: 14179,
+ text: ' did',
+ timestampMs: 14099,
+ },
+ {
+ confidence: null,
+ startMs: 14179,
+ endMs: 14300,
+ text: ' I',
+ timestampMs: 14239.5,
+ },
+ {
+ confidence: null,
+ startMs: 14300,
+ endMs: 14460,
+ text: ' do',
+ timestampMs: 14380,
+ },
+ {
+ confidence: null,
+ startMs: 14460,
+ endMs: 14819,
+ text: ' this?',
+ timestampMs: 14639.5,
+ },
+ {
+ confidence: null,
+ startMs: 14819,
+ endMs: 15299,
+ text: ' I',
+ timestampMs: 15059,
+ },
+ {
+ confidence: null,
+ startMs: 15299,
+ endMs: 15619,
+ text: ' found',
+ timestampMs: 15459,
+ },
+ {
+ confidence: null,
+ startMs: 15619,
+ endMs: 15779,
+ text: ' this',
+ timestampMs: 15699,
+ },
+ {
+ confidence: null,
+ startMs: 15779,
+ endMs: 16338.999999999998,
+ text: ' interesting',
+ timestampMs: 16059,
+ },
+ {
+ confidence: null,
+ startMs: 16338.999999999998,
+ endMs: 16619,
+ text: ' text',
+ timestampMs: 16479,
+ },
+ {
+ confidence: null,
+ startMs: 16619,
+ endMs: 16959,
+ text: ' behind',
+ timestampMs: 16789,
+ },
+ {
+ confidence: null,
+ startMs: 16959,
+ endMs: 17260,
+ text: ' video',
+ timestampMs: 17109.5,
+ },
+ {
+ confidence: null,
+ startMs: 17260,
+ endMs: 17559,
+ text: ' demo',
+ timestampMs: 17409.5,
+ },
+ {
+ confidence: null,
+ startMs: 17559,
+ endMs: 17739,
+ text: ' from',
+ timestampMs: 17649,
+ },
+ {
+ confidence: null,
+ startMs: 17739,
+ endMs: 18079,
+ text: ' Hugging',
+ timestampMs: 17909,
+ },
+ {
+ confidence: null,
+ startMs: 18079,
+ endMs: 18440,
+ text: ' Face,',
+ timestampMs: 18259.5,
+ },
+ {
+ confidence: null,
+ startMs: 18440,
+ endMs: 18680,
+ text: ' which',
+ timestampMs: 18560,
+ },
+ {
+ confidence: null,
+ startMs: 18680,
+ endMs: 19059,
+ text: ' works',
+ timestampMs: 18869.5,
+ },
+ {
+ confidence: null,
+ startMs: 19059,
+ endMs: 19579,
+ text: ' completely',
+ timestampMs: 19319,
+ },
+ {
+ confidence: null,
+ startMs: 19579,
+ endMs: 19879,
+ text: ' client',
+ timestampMs: 19729,
+ },
+ {
+ confidence: null,
+ startMs: 19879,
+ endMs: 20119,
+ text: ' side',
+ timestampMs: 19999,
+ },
+ {
+ confidence: null,
+ startMs: 20119,
+ endMs: 20319,
+ text: ' using',
+ timestampMs: 20219,
+ },
+ {
+ confidence: null,
+ startMs: 20319,
+ endMs: 21739,
+ text: ' Transformers.js',
+ timestampMs: 21029,
+ },
+ {
+ confidence: null,
+ startMs: 21739,
+ endMs: 21899,
+ text: ' and',
+ timestampMs: 21819,
+ },
+ {
+ confidence: null,
+ startMs: 21899,
+ endMs: 22020,
+ text: ' an',
+ timestampMs: 21959.5,
+ },
+ {
+ confidence: null,
+ startMs: 22020,
+ endMs: 22319,
+ text: ' open',
+ timestampMs: 22169.5,
+ },
+ {
+ confidence: null,
+ startMs: 22319,
+ endMs: 22600,
+ text: ' source',
+ timestampMs: 22459.5,
+ },
+ {
+ confidence: null,
+ startMs: 22600,
+ endMs: 22979,
+ text: ' model.',
+ timestampMs: 22789.5,
+ },
+ {
+ confidence: null,
+ startMs: 22979,
+ endMs: 23459,
+ text: ' However,',
+ timestampMs: 23219,
+ },
+ {
+ confidence: null,
+ startMs: 23459,
+ endMs: 24119,
+ text: ' unfortunately,',
+ timestampMs: 23789,
+ },
+ {
+ confidence: null,
+ startMs: 24119,
+ endMs: 24279,
+ text: ' the',
+ timestampMs: 24199,
+ },
+ {
+ confidence: null,
+ startMs: 24279,
+ endMs: 24639,
+ text: ' features',
+ timestampMs: 24459,
+ },
+ {
+ confidence: null,
+ startMs: 24639,
+ endMs: 24840,
+ text: ' are',
+ timestampMs: 24739.5,
+ },
+ {
+ confidence: null,
+ startMs: 24840,
+ endMs: 25199,
+ text: ' very',
+ timestampMs: 25019.5,
+ },
+ {
+ confidence: null,
+ startMs: 25199,
+ endMs: 25619,
+ text: ' limited,',
+ timestampMs: 25409,
+ },
+ {
+ confidence: null,
+ startMs: 25619,
+ endMs: 25840,
+ text: ' and',
+ timestampMs: 25729.5,
+ },
+ {
+ confidence: null,
+ startMs: 25840,
+ endMs: 25979,
+ text: ' we',
+ timestampMs: 25909.5,
+ },
+ {
+ confidence: null,
+ startMs: 25979,
+ endMs: 26319,
+ text: ' cannot',
+ timestampMs: 26149,
+ },
+ {
+ confidence: null,
+ startMs: 26319,
+ endMs: 26779,
+ text: ' insert',
+ timestampMs: 26549,
+ },
+ {
+ confidence: null,
+ startMs: 26779,
+ endMs: 26939,
+ text: ' an',
+ timestampMs: 26859,
+ },
+ {
+ confidence: null,
+ startMs: 26939,
+ endMs: 27459,
+ text: ' animated',
+ timestampMs: 27199,
+ },
+ {
+ confidence: null,
+ startMs: 27459,
+ endMs: 27680,
+ text: ' video',
+ timestampMs: 27569.5,
+ },
+ {
+ confidence: null,
+ startMs: 27680,
+ endMs: 28119,
+ text: ' layer.',
+ timestampMs: 27899.5,
+ },
+ {
+ confidence: null,
+ startMs: 28119,
+ endMs: 28699,
+ text: ' So',
+ timestampMs: 28409,
+ },
+ {
+ confidence: null,
+ startMs: 28699,
+ endMs: 28819,
+ text: ' I',
+ timestampMs: 28759,
+ },
+ {
+ confidence: null,
+ startMs: 28819,
+ endMs: 29319,
+ text: ' forked',
+ timestampMs: 29069,
+ },
+ {
+ confidence: null,
+ startMs: 29319,
+ endMs: 29459,
+ text: ' the',
+ timestampMs: 29389,
+ },
+ {
+ confidence: null,
+ startMs: 29459,
+ endMs: 29959,
+ text: ' project',
+ timestampMs: 29709,
+ },
+ {
+ confidence: null,
+ startMs: 29959,
+ endMs: 30119,
+ text: ' and',
+ timestampMs: 30039,
+ },
+ {
+ confidence: null,
+ startMs: 30119,
+ endMs: 30379,
+ text: ' spun',
+ timestampMs: 30249,
+ },
+ {
+ confidence: null,
+ startMs: 30379,
+ endMs: 30559,
+ text: ' up',
+ timestampMs: 30469,
+ },
+ {
+ confidence: null,
+ startMs: 30559,
+ endMs: 30739,
+ text: ' my',
+ timestampMs: 30649,
+ },
+ {
+ confidence: null,
+ startMs: 30739,
+ endMs: 30899,
+ text: ' own',
+ timestampMs: 30819,
+ },
+ {
+ confidence: null,
+ startMs: 30899,
+ endMs: 31299,
+ text: ' version',
+ timestampMs: 31099,
+ },
+ {
+ confidence: null,
+ startMs: 31299,
+ endMs: 31559,
+ text: ' that',
+ timestampMs: 31429,
+ },
+ {
+ confidence: null,
+ startMs: 31559,
+ endMs: 31939,
+ text: ' instead',
+ timestampMs: 31749,
+ },
+ {
+ confidence: null,
+ startMs: 31939,
+ endMs: 32219,
+ text: ' allows',
+ timestampMs: 32079,
+ },
+ {
+ confidence: null,
+ startMs: 32219,
+ endMs: 32340.000000000004,
+ text: ' me',
+ timestampMs: 32279.5,
+ },
+ {
+ confidence: null,
+ startMs: 32340.000000000004,
+ endMs: 32459.000000000004,
+ text: ' to',
+ timestampMs: 32399.500000000004,
+ },
+ {
+ confidence: null,
+ startMs: 32459.000000000004,
+ endMs: 32880,
+ text: ' export',
+ timestampMs: 32669.5,
+ },
+ {
+ confidence: null,
+ startMs: 32880,
+ endMs: 33020,
+ text: ' the',
+ timestampMs: 32950,
+ },
+ {
+ confidence: null,
+ startMs: 33020,
+ endMs: 33520,
+ text: ' foreground',
+ timestampMs: 33270,
+ },
+ {
+ confidence: null,
+ startMs: 33520,
+ endMs: 33680,
+ text: ' and',
+ timestampMs: 33600,
+ },
+ {
+ confidence: null,
+ startMs: 33680,
+ endMs: 34719,
+ text: ' background',
+ timestampMs: 34199.5,
+ },
+ {
+ confidence: null,
+ startMs: 34719,
+ endMs: 34899,
+ text: ' as',
+ timestampMs: 34809,
+ },
+ {
+ confidence: null,
+ startMs: 34899,
+ endMs: 35680,
+ text: ' transparent',
+ timestampMs: 35289.5,
+ },
+ {
+ confidence: null,
+ startMs: 35680,
+ endMs: 36479,
+ text: ' WebM',
+ timestampMs: 36079.5,
+ },
+ {
+ confidence: null,
+ startMs: 36479,
+ endMs: 36759,
+ text: ' video',
+ timestampMs: 36619,
+ },
+ {
+ confidence: null,
+ startMs: 36759,
+ endMs: 37119,
+ text: ' layers',
+ timestampMs: 36939,
+ },
+ {
+ confidence: null,
+ startMs: 37119,
+ endMs: 37380,
+ text: ' using',
+ timestampMs: 37249.5,
+ },
+ {
+ confidence: null,
+ startMs: 37380,
+ endMs: 37680,
+ text: ' Media',
+ timestampMs: 37530,
+ },
+ {
+ confidence: null,
+ startMs: 37680,
+ endMs: 38219,
+ text: ' Bunny.',
+ timestampMs: 37949.5,
+ },
+ {
+ confidence: null,
+ startMs: 38219,
+ endMs: 38439,
+ text: ' Now',
+ timestampMs: 38329,
+ },
+ {
+ confidence: null,
+ startMs: 38439,
+ endMs: 38540,
+ text: ' I',
+ timestampMs: 38489.5,
+ },
+ {
+ confidence: null,
+ startMs: 38540,
+ endMs: 38680,
+ text: ' can',
+ timestampMs: 38610,
+ },
+ {
+ confidence: null,
+ startMs: 38680,
+ endMs: 39000,
+ text: ' drag',
+ timestampMs: 38840,
+ },
+ {
+ confidence: null,
+ startMs: 39000,
+ endMs: 39239,
+ text: ' both',
+ timestampMs: 39119.5,
+ },
+ {
+ confidence: null,
+ startMs: 39239,
+ endMs: 39579,
+ text: ' layers',
+ timestampMs: 39409,
+ },
+ {
+ confidence: null,
+ startMs: 39579,
+ endMs: 39819,
+ text: ' into',
+ timestampMs: 39699,
+ },
+ {
+ confidence: null,
+ startMs: 39819,
+ endMs: 40340,
+ text: ' Remotion',
+ timestampMs: 40079.5,
+ },
+ {
+ confidence: null,
+ startMs: 40340,
+ endMs: 40520,
+ text: ' and',
+ timestampMs: 40430,
+ },
+ {
+ confidence: null,
+ startMs: 40520,
+ endMs: 40639,
+ text: ' put',
+ timestampMs: 40579.5,
+ },
+ {
+ confidence: null,
+ startMs: 40639,
+ endMs: 40759,
+ text: ' an',
+ timestampMs: 40699,
+ },
+ {
+ confidence: null,
+ startMs: 40759,
+ endMs: 41319,
+ text: ' HTML',
+ timestampMs: 41039,
+ },
+ {
+ confidence: null,
+ startMs: 41319,
+ endMs: 41639,
+ text: ' layer',
+ timestampMs: 41479,
+ },
+ {
+ confidence: null,
+ startMs: 41639,
+ endMs: 41759,
+ text: ' in',
+ timestampMs: 41699,
+ },
+ {
+ confidence: null,
+ startMs: 41759,
+ endMs: 42479,
+ text: ' between',
+ timestampMs: 42119,
+ },
+ {
+ confidence: null,
+ startMs: 42479,
+ endMs: 42739,
+ text: ' using',
+ timestampMs: 42609,
+ },
+ {
+ confidence: null,
+ startMs: 42739,
+ endMs: 42860,
+ text: ' an',
+ timestampMs: 42799.5,
+ },
+ {
+ confidence: null,
+ startMs: 42860,
+ endMs: 43379,
+ text: ' agent',
+ timestampMs: 43119.5,
+ },
+ {
+ confidence: null,
+ startMs: 43379,
+ endMs: 43659,
+ text: ' or',
+ timestampMs: 43519,
+ },
+ {
+ confidence: null,
+ startMs: 43659,
+ endMs: 43840,
+ text: ' by',
+ timestampMs: 43749.5,
+ },
+ {
+ confidence: null,
+ startMs: 43840,
+ endMs: 44079,
+ text: ' going',
+ timestampMs: 43959.5,
+ },
+ {
+ confidence: null,
+ startMs: 44079,
+ endMs: 44299,
+ text: ' into',
+ timestampMs: 44189,
+ },
+ {
+ confidence: null,
+ startMs: 44299,
+ endMs: 44419,
+ text: ' the',
+ timestampMs: 44359,
+ },
+ {
+ confidence: null,
+ startMs: 44419,
+ endMs: 45219,
+ text: ' code.',
+ timestampMs: 44819,
+ },
+ {
+ confidence: null,
+ startMs: 45219,
+ endMs: 45319,
+ text: ' The',
+ timestampMs: 45269,
+ },
+ {
+ confidence: null,
+ startMs: 45319,
+ endMs: 45719,
+ text: ' result,',
+ timestampMs: 45519,
+ },
+ {
+ confidence: null,
+ startMs: 45719,
+ endMs: 45819,
+ text: ' in',
+ timestampMs: 45769,
+ },
+ {
+ confidence: null,
+ startMs: 45819,
+ endMs: 45959,
+ text: ' my',
+ timestampMs: 45889,
+ },
+ {
+ confidence: null,
+ startMs: 45959,
+ endMs: 46459,
+ text: ' opinion,',
+ timestampMs: 46209,
+ },
+ {
+ confidence: null,
+ startMs: 46459,
+ endMs: 46979,
+ text: ' is',
+ timestampMs: 46719,
+ },
+ {
+ confidence: null,
+ startMs: 46979,
+ endMs: 47299,
+ text: ' super',
+ timestampMs: 47139,
+ },
+ {
+ confidence: null,
+ startMs: 47299,
+ endMs: 47739,
+ text: ' fresh.',
+ timestampMs: 47519,
+ },
+ {
+ confidence: null,
+ startMs: 47739,
+ endMs: 48259,
+ text: ' If',
+ timestampMs: 47999,
+ },
+ {
+ confidence: null,
+ startMs: 48259,
+ endMs: 48360,
+ text: ' you',
+ timestampMs: 48309.5,
+ },
+ {
+ confidence: null,
+ startMs: 48360,
+ endMs: 48619,
+ text: ' also',
+ timestampMs: 48489.5,
+ },
+ {
+ confidence: null,
+ startMs: 48619,
+ endMs: 48799,
+ text: ' want',
+ timestampMs: 48709,
+ },
+ {
+ confidence: null,
+ startMs: 48799,
+ endMs: 48919,
+ text: ' to',
+ timestampMs: 48859,
+ },
+ {
+ confidence: null,
+ startMs: 48919,
+ endMs: 49000,
+ text: ' see',
+ timestampMs: 48959.5,
+ },
+ {
+ confidence: null,
+ startMs: 49000,
+ endMs: 49099,
+ text: ' a',
+ timestampMs: 49049.5,
+ },
+ {
+ confidence: null,
+ startMs: 49099,
+ endMs: 49599,
+ text: ' breakdown',
+ timestampMs: 49349,
+ },
+ {
+ confidence: null,
+ startMs: 49599,
+ endMs: 49719,
+ text: ' of',
+ timestampMs: 49659,
+ },
+ {
+ confidence: null,
+ startMs: 49719,
+ endMs: 49939,
+ text: ' how',
+ timestampMs: 49829,
+ },
+ {
+ confidence: null,
+ startMs: 49939,
+ endMs: 50180,
+ text: ' I',
+ timestampMs: 50059.5,
+ },
+ {
+ confidence: null,
+ startMs: 50180,
+ endMs: 50779,
+ text: ' animated',
+ timestampMs: 50479.5,
+ },
+ {
+ confidence: null,
+ startMs: 50779,
+ endMs: 50939,
+ text: ' the',
+ timestampMs: 50859,
+ },
+ {
+ confidence: null,
+ startMs: 50939,
+ endMs: 51340,
+ text: ' lyrics',
+ timestampMs: 51139.5,
+ },
+ {
+ confidence: null,
+ startMs: 51340,
+ endMs: 51579,
+ text: ' using',
+ timestampMs: 51459.5,
+ },
+ {
+ confidence: null,
+ startMs: 51579,
+ endMs: 51860,
+ text: ' vibe',
+ timestampMs: 51719.5,
+ },
+ {
+ confidence: null,
+ startMs: 51860,
+ endMs: 52279,
+ text: ' coding,',
+ timestampMs: 52069.5,
+ },
+ {
+ confidence: null,
+ startMs: 52279,
+ endMs: 52919,
+ text: ' follow',
+ timestampMs: 52599,
+ },
+ {
+ confidence: null,
+ startMs: 52919,
+ endMs: 53159,
+ text: ' me',
+ timestampMs: 53039,
+ },
+ {
+ confidence: null,
+ startMs: 53159,
+ endMs: 53279,
+ text: ' for',
+ timestampMs: 53219,
+ },
+ {
+ confidence: null,
+ startMs: 53279,
+ endMs: 53659,
+ text: ' future',
+ timestampMs: 53469,
+ },
+ {
+ confidence: null,
+ startMs: 53659,
+ endMs: 54266.666666666664,
+ text: ' videos',
+ timestampMs: 53962.833333,
+ },
+ ]}
+ />
+ );
+};
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 3f950100be..8f8f7d08a4 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -17,10 +17,10 @@ import {NativeBufferState} from './BufferState/Simple';
import {NativeBufferStateForVideo} from './BufferState/Video';
import {CancelRender} from './CancelRender';
import {
- AnimatedCaptions,
CAPTIONS_DURATION_IN_FRAMES,
CAPTIONS_HEIGHT,
} from './CaptionsTester/AnimatedCaptions';
+import {AnimatedCaptionsComposition} from './CaptionsTester/AnimatedCaptionsComposition';
import {ClassSerialization} from './ClassSerialization';
import {ColorInterpolation} from './ColorInterpolation';
import {ComplexSounds} from './ComplexSounds';
@@ -438,7 +438,7 @@ export const Index: React.FC = () => {
/>
<Composition
id="captions-tester"
- component={AnimatedCaptions}
+ component={AnimatedCaptionsComposition}
durationInFrames={CAPTIONS_DURATION_IN_FRAMES}
fps={30}
width={1080}
diff --git a/packages/studio-server/src/codemods/update-inline-caption-patches.ts b/packages/studio-server/src/codemods/update-inline-caption-patches.ts
new file mode 100644
index 0000000000..e33d8ef9c7
--- /dev/null
+++ b/packages/studio-server/src/codemods/update-inline-caption-patches.ts
@@ -0,0 +1,280 @@
+import type {Expression, ObjectExpression, ObjectProperty} from '@babel/types';
+import type {CaptionPatch} from '@remotion/studio-shared';
+import type {SequenceNodePath} from 'remotion';
+import {findJsxElementNodeAtNodePath} from '../preview-server/routes/can-update-sequence-props';
+import {parseAst} from './parse-ast';
+
+const captionKeys = [
+ 'text',
+ 'startMs',
+ 'endMs',
+ 'timestampMs',
+ 'confidence',
+] as const;
+
+type CaptionKey = (typeof captionKeys)[number];
+type StaticCaption = CaptionPatch['before'];
+
+const getPropertyKey = (property: ObjectProperty): string | null => {
+ if (property.key.type === 'Identifier') {
+ return property.key.name;
+ }
+
+ if (property.key.type === 'StringLiteral') {
+ return property.key.value;
+ }
+
+ return null;
+};
+
+const getStaticValue = (value: Expression): string | number | null => {
+ if (value.type === 'StringLiteral' || value.type === 'NumericLiteral') {
+ return value.value;
+ }
+
+ if (value.type === 'NullLiteral') {
+ return null;
+ }
+
+ throw new Error('Captions must use static literal values to be edited');
+};
+
+const getStaticCaption = (expression: ObjectExpression): StaticCaption => {
+ const values = new Map<string, string | number | null>();
+ for (const property of expression.properties) {
+ if (property.type !== 'ObjectProperty' || property.computed) {
+ throw new Error(
+ 'Captions must use static object properties to be edited',
+ );
+ }
+
+ const key = getPropertyKey(property);
+ if (key !== null && captionKeys.includes(key as CaptionKey)) {
+ values.set(key, getStaticValue(property.value as Expression));
+ }
+ }
+
+ const text = values.get('text');
+ const startMs = values.get('startMs');
+ const endMs = values.get('endMs');
+ const timestampMs = values.get('timestampMs');
+ const confidence = values.get('confidence');
+ if (
+ typeof text !== 'string' ||
+ typeof startMs !== 'number' ||
+ typeof endMs !== 'number' ||
+ (timestampMs !== null && typeof timestampMs !== 'number') ||
+ (confidence !== null && typeof confidence !== 'number')
+ ) {
+ throw new Error(
+ 'Captions must have the standard static caption shape to edit',
+ );
+ }
+
+ return {text, startMs, endMs, timestampMs, confidence};
+};
+
+const isCaptionKey = (key: string): key is CaptionKey =>
+ captionKeys.includes(key as CaptionKey);
+
+const getReplacementValue = ({
+ value,
+ previous,
+}: {
+ value: string | number | null;
+ previous: Expression;
+}): string => {
+ if (value === null || typeof value === 'number') {
+ return String(value);
+ }
+
+ if (
+ previous.type === 'StringLiteral' &&
+ typeof previous.extra?.raw === 'string' &&
+ previous.extra.raw.startsWith("'")
+ ) {
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
+ }
+
+ return JSON.stringify(value);
+};
+
+const getSourceValueRange = ({
+ input,
+ property,
+ key,
+}: {
+ input: string;
+ property: ObjectProperty;
+ key: string;
+}): {start: number; end: number} => {
+ const line = property.loc?.start.line;
+ if (line === null || line === undefined) {
+ throw new Error(`Could not locate caption ${key} in the source file`);
+ }
+
+ const lines = input.split('\n');
+ const lineStart = lines
+ .slice(0, line - 1)
+ .reduce((length, current) => length + current.length + 1, 0);
+ const sourceLine = lines[line - 1];
+ if (sourceLine === undefined) {
+ throw new Error(`Could not locate caption ${key} in the source file`);
+ }
+
+ const keyStart = sourceLine.indexOf(key);
+ const valueStart = sourceLine.indexOf(':', keyStart) + 1;
+ const rawValue: string =
+ property.value.type === 'StringLiteral' &&
+ typeof property.value.extra?.raw === 'string'
+ ? property.value.extra.raw
+ : property.value.type === 'StringLiteral'
+ ? JSON.stringify(property.value.value)
+ : String(getStaticValue(property.value as Expression));
+ const valueOffset = sourceLine.indexOf(rawValue, valueStart);
+ if (keyStart === -1 || valueOffset === -1) {
+ throw new Error(`Could not locate caption ${key} in the source file`);
+ }
+
+ return {
+ start: lineStart + valueOffset,
+ end: lineStart + valueOffset + rawValue.length,
+ };
+};
+
+const updateCaption = ({
+ input,
+ caption,
+ patch,
+}: {
+ input: string;
+ caption: ObjectExpression;
+ patch: CaptionPatch;
+}): {changedFields: string[]; replacements: SourceReplacement[]} => {
+ const current = getStaticCaption(caption);
+ if (!captionKeys.every((key) => current[key] === patch.before[key])) {
+ throw new Error(
+ `Caption ${patch.index} changed in the source file before this edit could be saved`,
+ );
+ }
+
+ const changedKeys = Object.keys(patch.changes);
+ if (changedKeys.length === 0 || !changedKeys.every(isCaptionKey)) {
+ throw new Error('Caption patches must change at least one caption field');
+ }
+
+ const replacements: SourceReplacement[] = [];
+ for (const key of changedKeys) {
+ const value = patch.changes[key];
+ if (
+ (key === 'text' && typeof value !== 'string') ||
+ ((key === 'startMs' || key === 'endMs') &&
+ (typeof value !== 'number' || !Number.isFinite(value))) ||
+ ((key === 'timestampMs' || key === 'confidence') &&
+ value !== null &&
+ (typeof value !== 'number' || !Number.isFinite(value)))
+ ) {
+ throw new Error(`Caption ${key} has an invalid value`);
+ }
+
+ const property = caption.properties.find((candidate) => {
+ return (
+ candidate.type === 'ObjectProperty' &&
+ !candidate.computed &&
+ getPropertyKey(candidate) === key
+ );
+ });
+ if (!property || property.type !== 'ObjectProperty') {
+ throw new Error(`Caption ${patch.index} is missing ${key}`);
+ }
+
+ const {start, end} = getSourceValueRange({input, property, key});
+ replacements.push({
+ start,
+ end,
+ value: getReplacementValue({
+ value: value as string | number | null,
+ previous: property.value as Expression,
+ }),
+ });
+ }
+
+ return {changedFields: changedKeys, replacements};
+};
+
+type SourceReplacement = {
+ start: number;
+ end: number;
+ value: string;
+};
+
+export const updateInlineCaptionPatches = ({
+ input,
+ nodePath,
+ patches,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ patches: CaptionPatch[];
+}): {output: string; logLine: number; changedFields: string[][]} => {
+ if (patches.length === 0) {
+ throw new Error('Expected at least one caption patch');
+ }
+
+ const ast = parseAst(input);
+ const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
+ if (!jsxElement) {
+ throw new Error(
+ 'Could not find a JSX element at the specified line to update',
+ );
+ }
+
+ const captionsAttribute = jsxElement.openingElement.attributes?.find(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'captions',
+ );
+ if (
+ !captionsAttribute ||
+ captionsAttribute.type !== 'JSXAttribute' ||
+ captionsAttribute.value?.type !== 'JSXExpressionContainer' ||
+ captionsAttribute.value.expression.type !== 'ArrayExpression'
+ ) {
+ throw new Error('Captions must be an inline JSX array to edit them');
+ }
+
+ const captions = captionsAttribute.value.expression.elements;
+ const changedFields: string[][] = [];
+ const replacements: SourceReplacement[] = [];
+ for (const patch of patches) {
+ if (!Number.isInteger(patch.index) || patch.index < 0) {
+ throw new Error('Caption patch index must be a non-negative integer');
+ }
+
+ const caption = captions[patch.index];
+ if (!caption || caption.type !== 'ObjectExpression') {
+ throw new Error(`Could not find inline caption ${patch.index}`);
+ }
+
+ const result = updateCaption({input, caption, patch});
+ changedFields.push(result.changedFields);
+ replacements.push(...result.replacements);
+ }
+
+ const output = replacements
+ .sort((a, b) => b.start - a.start)
+ .reduce(
+ (current, replacement) =>
+ current.slice(0, replacement.start) +
+ replacement.value +
+ current.slice(replacement.end),
+ input,
+ );
+
+ return {
+ output,
+ logLine: jsxElement.openingElement.loc?.start.line ?? 1,
+ changedFields,
+ };
+};
diff --git a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
index 0723d1533a..60c49e8a29 100644
--- a/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
+++ b/packages/studio-server/src/preview-server/routes/save-sequence-props.ts
@@ -2,6 +2,7 @@ import {readFileSync} from 'node:fs';
import {RenderInternals} from '@remotion/renderer';
import type {
AddSequenceKeyframe,
+ SaveInlineCaptionPatchesRequest,
MoveEffectKeyframe,
MoveSequenceKeyframe,
SaveSequencePropEdit,
@@ -10,6 +11,7 @@ import type {
SaveSequencePropsResult,
} from '@remotion/studio-shared';
import {getAllSchemaKeys, getAssetSchemaKeys} from '@remotion/studio-shared';
+import {updateInlineCaptionPatches} from '../../codemods/update-inline-caption-patches';
import {
updateEffectKeyframes,
updateSequenceKeyframes,
@@ -49,6 +51,7 @@ type ResolvedSequencePropEdit = {
type SequencePropEditGroup = {
fileRelativeToRoot: string;
edits: ResolvedSequencePropEdit[];
+ captionPatches: SaveInlineCaptionPatchesRequest[];
addedKeyframes: AddSequenceKeyframe[];
movedSequenceKeyframes: ResolvedSequenceKeyframe[];
effectKeyframes: ResolvedEffectKeyframe[];
@@ -103,6 +106,14 @@ type SequenceKeyframeLog = {
formatted: boolean;
};
+type CaptionPatchLog = {
+ fileRelativeToRoot: string;
+ line: number;
+ index: number;
+ oldValueString: string;
+ newValueString: string;
+};
+
type EffectKeyframeLog = {
fileRelativeToRoot: string;
line: number;
@@ -168,6 +179,7 @@ export const saveSequencePropsHandler: ApiHandler<
edits,
addedKeyframes,
movedKeyframes,
+ captionPatches = [],
clientId,
undoLabel,
redoLabel,
@@ -186,6 +198,7 @@ export const saveSequencePropsHandler: ApiHandler<
keyframesToMove.effectKeyframes.length;
if (
edits.length === 0 &&
+ captionPatches.length === 0 &&
keyframesToAdd.length === 0 &&
totalKeyframeMoves === 0
) {
@@ -194,7 +207,7 @@ export const saveSequencePropsHandler: ApiHandler<
RenderInternals.Log.trace(
{indent: false, logLevel},
- `[save-sequence-props] Received request with ${edits.length} edit(s), ${keyframesToAdd.length} added keyframe(s), and ${totalKeyframeMoves} moved keyframe(s)`,
+ `[save-sequence-props] Received request with ${edits.length} edit(s), ${captionPatches.length} caption patch request(s), ${keyframesToAdd.length} added keyframe(s), and ${totalKeyframeMoves} moved keyframe(s)`,
);
const editGroups = new Map<string, SequencePropEditGroup>();
@@ -212,6 +225,7 @@ export const saveSequencePropsHandler: ApiHandler<
const group = editGroups.get(absolutePath) ?? {
fileRelativeToRoot,
edits: [],
+ captionPatches: [],
addedKeyframes: [],
movedSequenceKeyframes: [],
effectKeyframes: [],
@@ -234,6 +248,24 @@ export const saveSequencePropsHandler: ApiHandler<
editGroups.set(absolutePath, group);
}
+ for (const captionPatch of captionPatches) {
+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
+ remotionRoot,
+ fileName: captionPatch.fileName,
+ action: 'modify',
+ });
+ const group = editGroups.get(absolutePath) ?? {
+ fileRelativeToRoot,
+ edits: [],
+ captionPatches: [],
+ addedKeyframes: [],
+ movedSequenceKeyframes: [],
+ effectKeyframes: [],
+ };
+ group.captionPatches.push(captionPatch);
+ editGroups.set(absolutePath, group);
+ }
+
for (const keyframe of keyframesToAdd) {
const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
remotionRoot,
@@ -243,6 +275,7 @@ export const saveSequencePropsHandler: ApiHandler<
const group = editGroups.get(absolutePath) ?? {
fileRelativeToRoot,
edits: [],
+ captionPatches: [],
addedKeyframes: [],
movedSequenceKeyframes: [],
effectKeyframes: [],
@@ -263,6 +296,7 @@ export const saveSequencePropsHandler: ApiHandler<
const group = editGroups.get(absolutePath) ?? {
fileRelativeToRoot,
edits: [],
+ captionPatches: [],
addedKeyframes: [],
movedSequenceKeyframes: [],
effectKeyframes: [],
@@ -280,6 +314,7 @@ export const saveSequencePropsHandler: ApiHandler<
const group = editGroups.get(absolutePath) ?? {
fileRelativeToRoot,
edits: [],
+ captionPatches: [],
addedKeyframes: [],
movedSequenceKeyframes: [],
effectKeyframes: [],
@@ -292,6 +327,7 @@ export const saveSequencePropsHandler: ApiHandler<
const outputByPath = new Map<string, string>();
const resultByIndex = new Map<number, SequencePropEditResult>();
const sequenceKeyframeLogs: SequenceKeyframeLog[] = [];
+ const captionPatchLogs: CaptionPatchLog[] = [];
const effectKeyframeLogs: EffectKeyframeLog[] = [];
for (const [absolutePath, group] of editGroups) {
@@ -326,6 +362,40 @@ export const saveSequencePropsHandler: ApiHandler<
}
}
+ for (const captionPatchRequest of group.captionPatches) {
+ const result = updateInlineCaptionPatches({
+ input: output,
+ nodePath: captionPatchRequest.nodePath.nodePath,
+ patches: captionPatchRequest.patches,
+ });
+ output = result.output;
+ firstLogLine = Math.min(firstLogLine, result.logLine);
+ for (const [index, patch] of captionPatchRequest.patches.entries()) {
+ const changedFields = result.changedFields[index];
+ if (!changedFields) {
+ throw new Error('Could not determine changed caption fields');
+ }
+
+ captionPatchLogs.push({
+ fileRelativeToRoot: group.fileRelativeToRoot,
+ line: result.logLine,
+ index: patch.index,
+ oldValueString: changedFields
+ .map(
+ (field) =>
+ `${field}: ${patch.before[field as keyof typeof patch.before]}`,
+ )
+ .join(', '),
+ newValueString: changedFields
+ .map(
+ (field) =>
+ `${field}: ${patch.changes[field as keyof typeof patch.changes]}`,
+ )
+ .join(', '),
+ });
+ }
+ }
+
for (const keyframeGroup of groupBy(group.addedKeyframes, (keyframe) =>
JSON.stringify(keyframe.nodePath.nodePath),
)) {
@@ -483,7 +553,9 @@ export const saveSequencePropsHandler: ApiHandler<
const undoMessage = `↩️ ${undoLabel}`;
const redoMessage = `↪️ ${redoLabel}`;
- const suppressHmr = shouldSuppressHmrForSequencePropEdits(edits);
+ const suppressHmr =
+ captionPatches.length === 0 &&
+ shouldSuppressHmrForSequencePropEdits(edits);
pushTransactionToUndoStack({
snapshots,
@@ -525,6 +597,21 @@ export const saveSequencePropsHandler: ApiHandler<
}
}
+ for (const log of captionPatchLogs) {
+ logUpdate({
+ fileRelativeToRoot: log.fileRelativeToRoot,
+ line: log.line,
+ key: `captions[${log.index}]`,
+ oldValueString: log.oldValueString,
+ newValueString: log.newValueString,
+ defaultValueString: null,
+ formatted: true,
+ logLevel,
+ removedProps: [],
+ addedProps: [],
+ });
+ }
+
for (const log of sequenceKeyframeLogs) {
logUpdate({
fileRelativeToRoot: log.fileRelativeToRoot,
@@ -560,7 +647,7 @@ export const saveSequencePropsHandler: ApiHandler<
const statusTargets = [
...new Map(
- [...edits, ...keyframesToAdd].map((target) => [
+ [...edits, ...captionPatches, ...keyframesToAdd].map((target) => [
JSON.stringify(target.nodePath),
target,
]),
diff --git a/packages/studio-server/src/test/save-sequence-props.test.ts b/packages/studio-server/src/test/save-sequence-props.test.ts
index e46b5aff00..a6f58b6543 100644
--- a/packages/studio-server/src/test/save-sequence-props.test.ts
+++ b/packages/studio-server/src/test/save-sequence-props.test.ts
@@ -30,6 +30,14 @@ const starSchema = {
},
} satisfies InteractivitySchema;
+const captionsSchema = {
+ captions: {
+ type: 'remotion-captions',
+ default: undefined,
+ keyframable: false,
+ },
+} satisfies InteractivitySchema;
+
test('saveSequenceProps suppresses HMR for regular visual prop edits', () => {
expect(
shouldSuppressHmrForSequencePropEdits([
@@ -99,6 +107,106 @@ test('saveSequenceProps forwards element schemas to the codemod', () => {
});
});
+test('saveSequenceProps saves inline caption patches as an undoable source edit', async () => {
+ clearUndoStackForTests();
+ const cleanupFileWatcher = setFileWatcherRegistry(
+ createFileWatcherRegistry(),
+ );
+ const cleanupLiveEvents = setLiveEventsListener({
+ addNewClientListener: () => () => undefined,
+ closeConnections: () => Promise.resolve(),
+ router: () => Promise.resolve(),
+ sendEventToClient: () => undefined,
+ sendEventToClientId: () => true,
+ });
+ const dir = mkdtempSync(join(tmpdir(), 'remotion-save-sequence-props-'));
+ const fileName = 'Comp.tsx';
+ const filePath = join(dir, fileName);
+ const input = `export const Comp = () => {
+ return (
+ <Captions
+ captions={[
+ {
+ text: 'First',
+ startMs: 0,
+ endMs: 1000,
+ timestampMs: 500,
+ confidence: null,
+ },
+ ]}
+ />
+ );
+};
+`;
+ const nodePath = {
+ absolutePath: fileName,
+ nodePath: lineColumnToNodePath(input, 3),
+ sequenceKeys: ['captions'],
+ effectKeys: [],
+ videoConfigValues: null,
+ };
+
+ try {
+ writeFileSync(filePath, input);
+
+ await saveSequencePropsHandler({
+ input: {
+ edits: [],
+ captionPatches: [
+ {
+ fileName,
+ nodePath,
+ schema: captionsSchema,
+ patches: [
+ {
+ index: 0,
+ before: {
+ text: 'First',
+ startMs: 0,
+ endMs: 1000,
+ timestampMs: 500,
+ confidence: null,
+ },
+ changes: {text: 'Updated'},
+ },
+ ],
+ },
+ ],
+ addedKeyframes: null,
+ movedKeyframes: null,
+ clientId: 'test-client',
+ undoLabel: 'Edit caption',
+ redoLabel: 'Edit caption',
+ },
+ entryPoint: '',
+ remotionRoot: dir,
+ request: {} as never,
+ response: {} as never,
+ logLevel: 'error',
+ methods: {
+ addJob: () => undefined,
+ cancelJob: () => undefined,
+ removeJob: () => undefined,
+ },
+ publicDir: '',
+ binariesDirectory: null,
+ configFile: null,
+ });
+
+ expect(readFileSync(filePath, 'utf-8')).toContain("text: 'Updated'");
+ expect(getUndoStack()).toHaveLength(1);
+ expect(getUndoStack()[0]?.suppressHmrOnFileRestore).toBe(false);
+
+ expect(popUndo()).toEqual({success: true});
+ expect(readFileSync(filePath, 'utf-8')).toBe(input);
+ } finally {
+ clearUndoStackForTests();
+ cleanupLiveEvents();
+ cleanupFileWatcher();
+ rmSync(dir, {force: true, recursive: true});
+ }
+});
+
test('saveSequenceProps batches sequence movement and keyframe movement into one undo entry', async () => {
clearUndoStackForTests();
const cleanupFileWatcher = setFileWatcherRegistry(
diff --git a/packages/studio-server/src/test/update-inline-caption-patches.test.ts b/packages/studio-server/src/test/update-inline-caption-patches.test.ts
new file mode 100644
index 0000000000..c913ae2c58
--- /dev/null
+++ b/packages/studio-server/src/test/update-inline-caption-patches.test.ts
@@ -0,0 +1,107 @@
+import {expect, test} from 'bun:test';
+import {updateInlineCaptionPatches} from '../codemods/update-inline-caption-patches';
+import {lineColumnToNodePath} from './test-utils';
+
+const input = `import {TimedCaptions} from './TimedCaptions';
+
+export const Example = () => {
+ return (
+ <TimedCaptions
+ captions={[
+ {
+ text: 'First',
+ startMs: 0,
+ endMs: 1000,
+ timestampMs: 500,
+ confidence: null,
+ },
+ {
+ text: 'Second',
+ startMs: 1000,
+ endMs: 2000,
+ timestampMs: 1500,
+ confidence: 0.9,
+ },
+ ]}
+ />
+ );
+};
+`;
+
+test('updates only the patched inline caption fields', () => {
+ const {output, changedFields} = updateInlineCaptionPatches({
+ input,
+ nodePath: lineColumnToNodePath(input, 5),
+ patches: [
+ {
+ index: 1,
+ // The browser preserves the source object's property insertion order.
+ before: {
+ confidence: 0.9,
+ startMs: 1000,
+ endMs: 2000,
+ text: 'Second',
+ timestampMs: 1500,
+ },
+ changes: {startMs: 1100, endMs: 2100},
+ },
+ ],
+ });
+
+ expect(changedFields).toEqual([['startMs', 'endMs']]);
+ expect(output).toBe(
+ input.replace(
+ "text: 'Second',\n\t\t\t\t\tstartMs: 1000,\n\t\t\t\t\tendMs: 2000,",
+ "text: 'Second',\n\t\t\t\t\tstartMs: 1100,\n\t\t\t\t\tendMs: 2100,",
+ ),
+ );
+});
+
+test('rejects a queued patch whose source caption has changed', () => {
+ expect(() =>
+ updateInlineCaptionPatches({
+ input,
+ nodePath: lineColumnToNodePath(input, 5),
+ patches: [
+ {
+ index: 0,
+ before: {
+ text: 'Different',
+ startMs: 0,
+ endMs: 1000,
+ timestampMs: 500,
+ confidence: null,
+ },
+ changes: {endMs: 900},
+ },
+ ],
+ }),
+ ).toThrow('Caption 0 changed in the source file');
+});
+
+test('rejects captions wrapped in a satisfies expression', () => {
+ const captionsWithSatisfies = input.replace(
+ '\t\t\t]}',
+ '\t\t\t] satisfies Caption[]}',
+ );
+
+ expect(() =>
+ updateInlineCaptionPatches({
+ input: captionsWithSatisfies,
+ nodePath: lineColumnToNodePath(captionsWithSatisfies, 5),
+ patches: [
+ {
+ index: 0,
+ before: {
+ text: 'First',
+ startMs: 0,
+ endMs: 1000,
+ timestampMs: 500,
+ confidence: null,
+ },
+ changes: {text: 'Updated'},
+ },
+ ],
+ }),
+ ).toThrow('Captions must be an inline JSX array');
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index d062947da8..cdb576d96b 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -344,8 +344,34 @@ export type SaveSequencePropEdit = {
sourceEdit: SaveSequencePropSourceEdit | null;
};
+export type CaptionPatch = {
+ index: number;
+ before: {
+ text: string;
+ startMs: number;
+ endMs: number;
+ timestampMs: number | null;
+ confidence: number | null;
+ };
+ changes: Partial<{
+ text: string;
+ startMs: number;
+ endMs: number;
+ timestampMs: number | null;
+ confidence: number | null;
+ }>;
+};
+
+export type SaveInlineCaptionPatchesRequest = {
+ fileName: string;
+ nodePath: SequencePropsSubscriptionKey;
+ schema: InteractivitySchema;
+ patches: CaptionPatch[];
+};
+
export type SaveSequencePropsRequest = {
edits: SaveSequencePropEdit[];
+ captionPatches?: SaveInlineCaptionPatchesRequest[];
addedKeyframes: AddSequenceKeyframe[] | null;
movedKeyframes: {
sequenceKeyframes: MoveSequenceKeyframe[];
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 6207be50cd..067cf7d0e6 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -20,6 +20,7 @@ export {
BatchUpdateSequenceKeyframeSettings,
CanUpdateDefaultPropsResponse,
CanUpdateSequencePropsRequest,
+ CaptionPatch,
CancelRenderRequest,
CancelRenderResponse,
CompositionComponentInfoRequest,
@@ -89,6 +90,7 @@ export {
SaveMultipleEffectPropsRequest,
SaveMultipleEffectPropsResponse,
SaveMultipleEffectPropsResult,
+ SaveInlineCaptionPatchesRequest,
SaveSequencePropEdit,
SaveSequencePropSourceEdit,
SaveSequencePropsRequest,
diff --git a/packages/studio-shared/src/keyframe-clipboard-data.ts b/packages/studio-shared/src/keyframe-clipboard-data.ts
index e3b7d0ed75..9fcccafc27 100644
--- a/packages/studio-shared/src/keyframe-clipboard-data.ts
+++ b/packages/studio-shared/src/keyframe-clipboard-data.ts
@@ -11,6 +11,7 @@ const KEYFRAME_CLIPBOARD_FIELD_TYPE_SUPPORT = {
array: false,
asset: false,
boolean: false,
+ 'remotion-captions': false,
color: true,
enum: false,
'font-family': false,
diff --git a/packages/studio-shared/src/keyframe-interpolation-function.ts b/packages/studio-shared/src/keyframe-interpolation-function.ts
index fc7298b91c..efcaa37c82 100644
--- a/packages/studio-shared/src/keyframe-interpolation-function.ts
+++ b/packages/studio-shared/src/keyframe-interpolation-function.ts
@@ -14,6 +14,7 @@ const KEYFRAME_FIELD_TYPE_SUPPORT = {
array: false,
asset: false,
boolean: false,
+ 'remotion-captions': false,
color: true,
enum: false,
'font-family': false,
@@ -37,6 +38,7 @@ const KEYFRAME_FIELD_TYPE_INTERPOLATION = {
array: 'unsupported',
asset: 'unsupported',
boolean: 'unsupported',
+ 'remotion-captions': 'unsupported',
color: 'interpolateColors',
enum: 'unsupported',
'font-family': 'unsupported',
diff --git a/packages/studio-shared/src/schema-field-info.ts b/packages/studio-shared/src/schema-field-info.ts
index 7cbf6a812e..95d80f54ae 100644
--- a/packages/studio-shared/src/schema-field-info.ts
+++ b/packages/studio-shared/src/schema-field-info.ts
@@ -162,6 +162,7 @@ const TIMELINE_SCHEMA_FIELD_TYPE_SUPPORT = {
array: true,
asset: true,
boolean: true,
+ 'remotion-captions': false,
color: true,
enum: true,
'font-family': true,
diff --git a/packages/studio-shared/src/test/schema-field-info.test.ts b/packages/studio-shared/src/test/schema-field-info.test.ts
index 40d9d1155c..b66c8bfa43 100644
--- a/packages/studio-shared/src/test/schema-field-info.test.ts
+++ b/packages/studio-shared/src/test/schema-field-info.test.ts
@@ -160,6 +160,24 @@ test('getEffectFieldsToShow sizes array fields from the current value', () => {
expect(colors?.rowHeight).toBe(SCHEMA_FIELD_ROW_HEIGHT * 4);
});
+test('getFieldsToShow leaves captions to the caption inspector', () => {
+ const fields = getFieldsToShow({
+ schema: {
+ captions: {
+ type: 'remotion-captions',
+ default: undefined,
+ keyframable: false,
+ },
+ },
+ currentRuntimeValueDotNotation: {captions: []},
+ getDragOverrides: () => ({}),
+ propStatuses: {},
+ nodePath,
+ });
+
+ expect(fields).toEqual([]);
+});
+
test('getFieldsToShow sorts fields by inspector group order', () => {
const fields = getFieldsToShow({
schema: {
diff --git a/packages/studio/package.json b/packages/studio/package.json
index 03e4767ead..dc646387aa 100644
--- a/packages/studio/package.json
+++ b/packages/studio/package.json
@@ -28,6 +28,7 @@
"semver": "7.5.3",
"remotion": "workspace:*",
"@remotion/canvas-capture": "workspace:*",
+ "@remotion/captions": "workspace:*",
"@remotion/player": "workspace:*",
"@remotion/media-utils": "workspace:*",
"@remotion/renderer": "workspace:*",
diff --git a/packages/studio/src/components/CaptionInspector.tsx b/packages/studio/src/components/CaptionInspector.tsx
new file mode 100644
index 0000000000..219ac768ad
--- /dev/null
+++ b/packages/studio/src/components/CaptionInspector.tsx
@@ -0,0 +1,63 @@
+import type {Caption} from '@remotion/captions';
+import React from 'react';
+import {LIGHT_TEXT} from '../helpers/colors';
+import {CaptionTextEditor} from './CaptionTextEditor';
+import {
+ InspectorSectionDivider,
+ InspectorSectionHeader,
+} from './InspectorPanel/common';
+import {
+ sectionHeaderEnd,
+ sectionHeaderRow,
+ sectionHeaderTitle,
+} from './InspectorPanel/styles';
+
+const readOnlyStatus: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontFamily: 'sans-serif',
+ fontSize: 12,
+ fontWeight: 'normal',
+ lineHeight: '16px',
+ marginLeft: 12,
+};
+
+export const CaptionInspector: React.FC<{
+ readonly captions: Caption[];
+ readonly onTextChange: (captions: Caption[]) => void;
+ readonly onTextSave: ((captions: Caption[]) => void) | null;
+ readonly onTextCancel: (() => void) | null;
+ readonly readOnly: boolean;
+ readonly readOnlyTitle: string | null;
+}> = ({
+ captions,
+ onTextChange,
+ onTextSave,
+ onTextCancel,
+ readOnly,
+ readOnlyTitle,
+}) => {
+ return (
+ <>
+ <InspectorSectionDivider />
+ <InspectorSectionHeader>
+ <div style={sectionHeaderRow}>
+ <div style={sectionHeaderTitle}>Captions</div>
+ <div style={sectionHeaderEnd}>
+ {readOnly ? (
+ <div style={readOnlyStatus} title={readOnlyTitle ?? undefined}>
+ Read only
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </InspectorSectionHeader>
+ <CaptionTextEditor
+ captions={captions}
+ onChange={onTextChange}
+ onSave={onTextSave}
+ onCancel={onTextCancel}
+ readOnly={readOnly}
+ />
+ </>
+ );
+};
diff --git a/packages/studio/src/components/CaptionTextEditor.tsx b/packages/studio/src/components/CaptionTextEditor.tsx
new file mode 100644
index 0000000000..d06bb0ce08
--- /dev/null
+++ b/packages/studio/src/components/CaptionTextEditor.tsx
@@ -0,0 +1,180 @@
+import type {Caption} from '@remotion/captions';
+import React, {useCallback, useEffect, useMemo, useRef} from 'react';
+import {BACKGROUND, LIGHT_TEXT, LINE_COLOR, WHITE} from '../helpers/colors';
+import {RemotionInput} from './NewComposition/RemInput';
+
+const container: React.CSSProperties = {
+ alignSelf: 'stretch',
+ backgroundColor: BACKGROUND,
+ display: 'flex',
+ flexDirection: 'column',
+ fontFamily: 'sans-serif',
+ width: '100%',
+};
+
+const list: React.CSSProperties = {
+ display: 'flex',
+ flexDirection: 'column',
+};
+
+const row: React.CSSProperties = {
+ alignItems: 'center',
+ borderBottom: `1px solid ${LINE_COLOR}`,
+ display: 'grid',
+ gap: 12,
+ gridTemplateColumns: '100px minmax(0, 1fr)',
+ padding: '5px 12px',
+};
+
+const timing: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontFamily: 'monospace',
+ fontSize: 11,
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: '16px',
+ textAlign: 'right',
+ whiteSpace: 'nowrap',
+};
+
+const empty: React.CSSProperties = {
+ color: LIGHT_TEXT,
+ fontFamily: 'sans-serif',
+ fontSize: 13,
+ lineHeight: '18px',
+ padding: 12,
+ textAlign: 'center',
+};
+
+const formatMilliseconds = (milliseconds: number): number => {
+ return Math.round(milliseconds);
+};
+
+export const CaptionTextEditor: React.FC<{
+ readonly captions: Caption[];
+ readonly onChange: (captions: Caption[]) => void;
+ readonly onSave: ((captions: Caption[]) => void) | null;
+ readonly onCancel: (() => void) | null;
+ readonly readOnly: boolean;
+}> = ({captions, onChange, onSave, onCancel, readOnly}) => {
+ const listRef = useRef<HTMLDivElement>(null);
+ const cancelledBlurIndexes = useRef(new Set<number>());
+ const dirtyRef = useRef(false);
+ const latestRef = useRef({captions, onSave});
+ latestRef.current = {captions, onSave};
+ const captionRows = useMemo(() => {
+ const occurrences = new Map<string, number>();
+ return captions.map((caption) => {
+ const signature = [
+ caption.startMs,
+ caption.endMs,
+ caption.timestampMs,
+ caption.confidence,
+ ].join('-');
+ const occurrence = occurrences.get(signature) ?? 0;
+ occurrences.set(signature, occurrence + 1);
+ return {caption, key: `${signature}-${occurrence}`};
+ });
+ }, [captions]);
+
+ const commitPending = useCallback(() => {
+ if (!dirtyRef.current) {
+ return;
+ }
+
+ dirtyRef.current = false;
+ latestRef.current.onSave?.(latestRef.current.captions);
+ }, []);
+
+ useEffect(() => {
+ return commitPending;
+ }, [commitPending]);
+
+ const updateText = useCallback(
+ (index: number, text: string) => {
+ if (latestRef.current.captions[index]?.text === text) {
+ return;
+ }
+
+ const nextCaptions = latestRef.current.captions.map(
+ (caption, captionIndex) => {
+ return captionIndex === index ? {...caption, text} : caption;
+ },
+ );
+ latestRef.current.captions = nextCaptions;
+ dirtyRef.current = true;
+ onChange(nextCaptions);
+ },
+ [onChange],
+ );
+
+ const focusSibling = useCallback((index: number) => {
+ const input = listRef.current?.querySelector<HTMLInputElement>(
+ `[data-caption-index="${index}"]`,
+ );
+ input?.focus();
+ input?.scrollIntoView({block: 'nearest'});
+ }, []);
+
+ return (
+ <div style={container}>
+ <div ref={listRef} style={list}>
+ {captions.length === 0 ? <div style={empty}>No captions</div> : null}
+ {captionRows.map(({caption, key}, index) => {
+ return (
+ <div key={key} style={row}>
+ <div style={timing}>
+ {formatMilliseconds(caption.startMs)} →{' '}
+ {formatMilliseconds(caption.endMs)} ms
+ </div>
+ <RemotionInput
+ data-caption-index={index}
+ disabled={readOnly}
+ onBlur={(event) => {
+ if (cancelledBlurIndexes.current.delete(index)) {
+ return;
+ }
+
+ updateText(index, event.currentTarget.value);
+ commitPending();
+ }}
+ onChange={(event) => updateText(index, event.target.value)}
+ onKeyDown={(event) => {
+ if (
+ event.key === 'ArrowDown' &&
+ index < captions.length - 1
+ ) {
+ event.preventDefault();
+ focusSibling(index + 1);
+ }
+
+ if (event.key === 'ArrowUp' && index > 0) {
+ event.preventDefault();
+ focusSibling(index - 1);
+ }
+
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ cancelledBlurIndexes.current.add(index);
+ dirtyRef.current = false;
+ onCancel?.();
+ event.currentTarget.blur();
+ }
+ }}
+ rightAlign={false}
+ small
+ status="ok"
+ style={{
+ color: WHITE,
+ fontFamily: 'sans-serif',
+ fontSize: 12,
+ lineHeight: '16px',
+ }}
+ value={caption.text}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/studio/src/components/InlineCaptionInspector.tsx b/packages/studio/src/components/InlineCaptionInspector.tsx
new file mode 100644
index 0000000000..945a55f41d
--- /dev/null
+++ b/packages/studio/src/components/InlineCaptionInspector.tsx
@@ -0,0 +1,167 @@
+import type {Caption} from '@remotion/captions';
+import type {CaptionPatch} from '@remotion/studio-shared';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react';
+import type {SequenceControls, SequencePropsSubscriptionKey} from 'remotion';
+import {Internals} from 'remotion';
+import type {CodePosition} from '../error-overlay/react-overlay/utils/get-source-map';
+import {StudioServerConnectionCtx} from '../helpers/client-id';
+import {CaptionInspector} from './CaptionInspector';
+import {saveInlineCaptionPatches} from './Timeline/save-sequence-prop';
+
+const serializeCaptions = (captions: Caption[]): string => {
+ return JSON.stringify(captions);
+};
+
+const getCaptionPatches = ({
+ previous,
+ next,
+}: {
+ previous: Caption[];
+ next: Caption[];
+}): CaptionPatch[] | null => {
+ if (previous.length !== next.length) {
+ return null;
+ }
+
+ const patches: CaptionPatch[] = [];
+ for (const [index, before] of previous.entries()) {
+ const after = next[index];
+ if (!after) {
+ return null;
+ }
+
+ if (before.text !== after.text) {
+ patches.push({
+ index,
+ before,
+ changes: {text: after.text},
+ });
+ }
+ }
+
+ return patches;
+};
+
+export const InlineCaptionInspector: React.FC<{
+ readonly captions: Caption[];
+ readonly controls: SequenceControls;
+ readonly nodePath: SequencePropsSubscriptionKey;
+ readonly readOnlyStudio: boolean;
+ readonly validatedLocation: CodePosition;
+}> = ({captions, controls, nodePath, readOnlyStudio, validatedLocation}) => {
+ const {previewServerState} = useContext(StudioServerConnectionCtx);
+ const {propStatuses} = useContext(Internals.VisualModePropStatusesContext);
+ const {setPropStatuses, setDragOverrides, clearDragOverrides} = useContext(
+ Internals.VisualModeSettersContext,
+ );
+ const captionStatus = Internals.getPropStatusesCtx(
+ propStatuses,
+ nodePath,
+ )?.captions;
+ const clientId =
+ previewServerState.type === 'connected'
+ ? previewServerState.clientId
+ : null;
+ const canSave =
+ !readOnlyStudio && clientId !== null && captionStatus?.status === 'static';
+ const [draftCaptions, setDraftCaptions] = useState(captions);
+ const savedCaptions = useRef(captions);
+ const runtimeSignature = serializeCaptions(captions);
+ const lastRuntimeSignature = useRef(runtimeSignature);
+
+ useEffect(() => {
+ if (lastRuntimeSignature.current === runtimeSignature) {
+ return;
+ }
+
+ lastRuntimeSignature.current = runtimeSignature;
+ savedCaptions.current = captions;
+ setDraftCaptions(captions);
+ clearDragOverrides(nodePath);
+ }, [captions, clearDragOverrides, nodePath, runtimeSignature]);
+
+ const updateCaptions = useCallback(
+ (nextCaptions: Caption[]) => {
+ setDraftCaptions(nextCaptions);
+ setDragOverrides(
+ nodePath,
+ 'captions',
+ Internals.makeStaticDragOverride(nextCaptions),
+ );
+ },
+ [nodePath, setDragOverrides],
+ );
+
+ const cancelCaptions = useCallback(() => {
+ setDraftCaptions(savedCaptions.current);
+ clearDragOverrides(nodePath);
+ }, [clearDragOverrides, nodePath]);
+
+ const saveCaptions = useCallback(
+ (nextCaptions: Caption[]) => {
+ const patches = getCaptionPatches({
+ previous: savedCaptions.current,
+ next: nextCaptions,
+ });
+ setDraftCaptions(nextCaptions);
+
+ if (
+ !canSave ||
+ clientId === null ||
+ patches === null ||
+ patches.length === 0
+ ) {
+ clearDragOverrides(nodePath);
+ return;
+ }
+
+ savedCaptions.current = nextCaptions;
+ saveInlineCaptionPatches({
+ fileName: validatedLocation.source,
+ nodePath,
+ schema: controls.schema,
+ patches,
+ nextCaptions,
+ setPropStatuses,
+ clientId,
+ undoLabel: 'Update captions',
+ redoLabel: 'Update captions again',
+ });
+ clearDragOverrides(nodePath);
+ },
+ [
+ canSave,
+ clearDragOverrides,
+ clientId,
+ controls.schema,
+ nodePath,
+ setPropStatuses,
+ validatedLocation.source,
+ ],
+ );
+
+ const readOnlyTitle = readOnlyStudio
+ ? 'Caption editing is unavailable in read-only Studio'
+ : clientId === null
+ ? 'Caption editing requires a Studio server connection'
+ : captionStatus?.status === 'computed'
+ ? 'Captions must be a direct inline JSX array to edit them'
+ : 'Captions are not ready for editing';
+
+ return (
+ <CaptionInspector
+ captions={draftCaptions}
+ onTextChange={updateCaptions}
+ onTextSave={saveCaptions}
+ onTextCancel={cancelCaptions}
+ readOnly={!canSave}
+ readOnlyTitle={canSave ? null : readOnlyTitle}
+ />
+ );
+};
diff --git a/packages/studio/src/components/InspectorPanel.tsx b/packages/studio/src/components/InspectorPanel.tsx
index c62774f8c5..5576bca71b 100644
--- a/packages/studio/src/components/InspectorPanel.tsx
+++ b/packages/studio/src/components/InspectorPanel.tsx
@@ -46,7 +46,10 @@ export const InspectorPanel: React.FC<{
if (sameSequenceInspectorSelection) {
return (
<div style={container}>
- <SelectedInspector selection={sameSequenceInspectorSelection} />
+ <SelectedInspector
+ selection={sameSequenceInspectorSelection}
+ readOnlyStudio={readOnlyStudio}
+ />
</div>
);
}
@@ -62,7 +65,10 @@ export const InspectorPanel: React.FC<{
return (
<div style={container}>
- <SelectedInspector selection={selectedItems[0]} />
+ <SelectedInspector
+ selection={selectedItems[0]}
+ readOnlyStudio={readOnlyStudio}
+ />
</div>
);
};
diff --git a/packages/studio/src/components/InspectorPanel/SelectedInspector.tsx b/packages/studio/src/components/InspectorPanel/SelectedInspector.tsx
index 91b2ca8b8a..dc01c2e49d 100644
--- a/packages/studio/src/components/InspectorPanel/SelectedInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SelectedInspector.tsx
@@ -9,9 +9,15 @@ import {SequenceSelectionInspector} from './SequenceSelectionInspector';
export const SelectedInspector: React.FC<{
readonly selection: TimelineSelection;
-}> = ({selection}) => {
+ readonly readOnlyStudio: boolean;
+}> = ({selection, readOnlyStudio}) => {
if (isSequenceSectionSelection(selection)) {
- return <SequenceSelectionInspector selection={selection} />;
+ return (
+ <SequenceSelectionInspector
+ selection={selection}
+ readOnlyStudio={readOnlyStudio}
+ />
+ );
}
if (selection.type === 'keyframe') {
diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
index 40507b5133..60790d558d 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
@@ -207,7 +207,8 @@ const SequenceSourceActions: React.FC<{
const SequenceExpandedInspector: React.FC<{
readonly track: TimelineTrackData;
-}> = ({track}) => {
+ readonly readOnlyStudio: boolean;
+}> = ({track, readOnlyStudio}) => {
const {previewServerState} = useContext(StudioServerConnectionCtx);
const {selectedItems, selectItems} = useTimelineSelection();
const sourceLocation = useSequenceInspectorSourceLocation(track.sequence);
@@ -286,6 +287,7 @@ const SequenceExpandedInspector: React.FC<{
<>
<InspectorSequenceSection
sequence={track.sequence}
+ readOnlyStudio={readOnlyStudio}
validatedLocation={validatedLocation}
nodePathInfo={track.nodePathInfo}
keyframeDisplayOffset={track.keyframeDisplayOffset}
@@ -309,7 +311,8 @@ const SequenceExpandedInspector: React.FC<{
export const SequenceSelectionInspector: React.FC<{
readonly selection: SequenceSectionSelection;
-}> = ({selection}) => {
+ readonly readOnlyStudio: boolean;
+}> = ({selection, readOnlyStudio}) => {
const track = useTrackForSelection(selection);
if (!track) {
@@ -322,6 +325,7 @@ export const SequenceSelectionInspector: React.FC<{
<SequenceExpandedInspector
key={stackKey ?? track.sequence.id}
track={track}
+ readOnlyStudio={readOnlyStudio}
/>
);
};
diff --git a/packages/studio/src/components/InspectorSequenceSection.tsx b/packages/studio/src/components/InspectorSequenceSection.tsx
index e9df27e15d..1d6702142d 100644
--- a/packages/studio/src/components/InspectorSequenceSection.tsx
+++ b/packages/studio/src/components/InspectorSequenceSection.tsx
@@ -1,3 +1,4 @@
+import type {Caption} from '@remotion/captions';
import React, {useCallback, useContext, useMemo, useState} from 'react';
import type {TSequence} from 'remotion';
import type {CodePosition} from '../error-overlay/react-overlay/utils/get-source-map';
@@ -17,6 +18,7 @@ import {Plus} from '../icons/plus';
import {ModalsContext} from '../state/modals';
import {AssetFileIcon} from './AssetFileIcon';
import {InlineAction} from './InlineAction';
+import {InlineCaptionInspector} from './InlineCaptionInspector';
import {InspectorSection} from './InspectorPanel/common';
import {sectionHeaderRow, sectionHeaderTitle} from './InspectorPanel/styles';
import {getAssetSearchQueryForComponent} from './QuickSwitcher/asset-search';
@@ -202,12 +204,14 @@ export const hasSequenceControls = (
export const InspectorSequenceSection: React.FC<{
readonly sequence: SequenceWithControls;
+ readonly readOnlyStudio: boolean;
readonly validatedLocation: CodePosition;
readonly nodePathInfo: SequenceNodePathInfo;
readonly keyframeDisplayOffset: number;
readonly renderTransformControls: () => React.ReactNode;
}> = ({
sequence,
+ readOnlyStudio,
validatedLocation,
nodePathInfo,
keyframeDisplayOffset,
@@ -355,6 +359,13 @@ export const InspectorSequenceSection: React.FC<{
);
const {schema} = sequence.controls;
+ const inlineCaptionValue =
+ schema.captions?.type === 'remotion-captions'
+ ? sequence.controls.currentRuntimeValueDotNotation.captions
+ : null;
+ const inlineCaptions = Array.isArray(inlineCaptionValue)
+ ? (inlineCaptionValue as Caption[])
+ : null;
const showEffectsSection =
nodePathInfo.supportsEffects || effectRows.length > 0;
const canAddEffect =
@@ -417,7 +428,11 @@ export const InspectorSequenceSection: React.FC<{
);
};
- if (controlRows.length === 0 && !showEffectsSection) {
+ if (
+ controlRows.length === 0 &&
+ !showEffectsSection &&
+ inlineCaptions === null
+ ) {
return (
<div style={container}>
<InspectorSection header="Controls">
@@ -440,6 +455,15 @@ export const InspectorSequenceSection: React.FC<{
))}
</TimelineSelectionOrderProvider>
) : null}
+ {inlineCaptions ? (
+ <InlineCaptionInspector
+ captions={inlineCaptions}
+ controls={sequence.controls}
+ nodePath={nodePathInfo.sequenceSubscriptionKey}
+ readOnlyStudio={readOnlyStudio}
+ validatedLocation={validatedLocation}
+ />
+ ) : null}
{showEffectsSection ? (
<InspectorSection header={effectsHeader}>
{effectRows.length > 0 ? (
diff --git a/packages/studio/src/components/Timeline/TimelinePrimitiveFieldValue.tsx b/packages/studio/src/components/Timeline/TimelinePrimitiveFieldValue.tsx
index e384dab5c3..855ffaf1cb 100644
--- a/packages/studio/src/components/Timeline/TimelinePrimitiveFieldValue.tsx
+++ b/packages/studio/src/components/Timeline/TimelinePrimitiveFieldValue.tsx
@@ -34,18 +34,32 @@ const assetInlineWrapper: React.CSSProperties = {
minWidth: 0,
};
+type CaptionsFieldSchema = Extract<
+ VisibleFieldSchema,
+ {type: 'remotion-captions'}
+>;
+
+type PrimitiveFieldSchema = Exclude<
+ VisibleFieldSchema,
+ ArrayFieldSchema | CaptionsFieldSchema
+>;
+
export type TimelinePrimitiveFieldInfo = Omit<
SchemaFieldInfo,
'fieldSchema' | 'typeName'
> & {
- readonly fieldSchema: Exclude<VisibleFieldSchema, ArrayFieldSchema>;
- readonly typeName: Exclude<VisibleFieldSchema['type'], 'array'>;
+ readonly fieldSchema: PrimitiveFieldSchema;
+ readonly typeName: PrimitiveFieldSchema['type'];
};
export const isTimelinePrimitiveFieldInfo = (
field: SchemaFieldInfo,
): field is TimelinePrimitiveFieldInfo => {
- return field.typeName !== 'array' && field.fieldSchema.type !== 'array';
+ return (
+ field.typeName !== 'array' &&
+ field.fieldSchema.type !== 'array' &&
+ field.fieldSchema.type !== 'remotion-captions'
+ );
};
export const TimelinePrimitiveFieldValue: React.FC<{
diff --git a/packages/studio/src/components/Timeline/save-sequence-prop.ts b/packages/studio/src/components/Timeline/save-sequence-prop.ts
index f3e712671b..c8efa41f32 100644
--- a/packages/studio/src/components/Timeline/save-sequence-prop.ts
+++ b/packages/studio/src/components/Timeline/save-sequence-prop.ts
@@ -1,6 +1,7 @@
import {
optimisticAddSequenceKeyframe,
optimisticUpdateForPropStatuses,
+ type CaptionPatch,
type SaveSequencePropSourceEdit,
} from '@remotion/studio-shared';
import type {
@@ -55,6 +56,52 @@ const serializeSequencePropValue = (value: unknown) => {
return {type: 'json' as const, serialized: JSON.stringify(value)};
};
+export const saveInlineCaptionPatches = ({
+ fileName,
+ nodePath,
+ schema,
+ patches,
+ nextCaptions,
+ setPropStatuses,
+ clientId,
+ undoLabel,
+ redoLabel,
+}: {
+ fileName: string;
+ nodePath: SequencePropsSubscriptionKey;
+ schema: InteractivitySchema;
+ patches: CaptionPatch[];
+ nextCaptions: unknown;
+ setPropStatuses: SetPropStatuses;
+ clientId: string;
+ undoLabel: string;
+ redoLabel: string;
+}): Promise<void> => {
+ return enqueueSavePropChange({
+ nodePath,
+ setPropStatuses,
+ applyOptimistic: (previous) =>
+ optimisticUpdateForPropStatuses({
+ previous,
+ fieldKey: 'captions',
+ value: nextCaptions,
+ defaultValue: null,
+ schema,
+ }),
+ apiCall: () =>
+ callApi('/api/save-sequence-props', {
+ edits: [],
+ captionPatches: [{fileName, nodePath, schema, patches}],
+ addedKeyframes: null,
+ movedKeyframes: null,
+ clientId,
+ undoLabel,
+ redoLabel,
+ }),
+ errorLabel: 'Could not save captions',
+ });
+};
+
export const saveSequenceProps = ({
changes,
addedKeyframes,
diff --git a/packages/studio/src/components/Timeline/timeline-field-display-utils.ts b/packages/studio/src/components/Timeline/timeline-field-display-utils.ts
index ab796b86a8..659d083ff2 100644
--- a/packages/studio/src/components/Timeline/timeline-field-display-utils.ts
+++ b/packages/studio/src/components/Timeline/timeline-field-display-utils.ts
@@ -393,6 +393,7 @@ export const formatTimelineFieldValueForDisplay = ({
case 'asset':
case 'array':
case 'boolean':
+ case 'remotion-captions':
case 'color':
case 'enum':
case 'font-family':