🎥 Make videos programmatically with React
Elements: Split timed captions element (#10060)
Elowenbf293f63c2b9
diff --git a/packages/docs/elements-sidebars.ts b/packages/docs/elements-sidebars.tsindex 20750ef56c..0c6ed31b8b 100644--- a/packages/docs/elements-sidebars.ts+++ b/packages/docs/elements-sidebars.ts@@ -56,7 +56,9 @@ const sidebars: SidebarsConfig = {'text/news-article-headline-highlight/index','text/strike-through/index','text/text-marker/index',- 'text/timed-captions/index',+ 'text/timed-captions-background/index',+ 'text/timed-captions-highlight/index',+ 'text/timed-captions-scale/index',],},],diff --git a/packages/docs/elements/text/timed-captions-background/index.mdx b/packages/docs/elements/text/timed-captions-background/index.mdxnew file mode 100644index 0000000000..13ff0322d1--- /dev/null+++ b/packages/docs/elements/text/timed-captions-background/index.mdx@@ -0,0 +1,12 @@+---+title: Background Timed Captions+description: Animated captions with word-level moving background styling.+image: https://remotion.media/elements/text-timed-captions-background-preview.png+---++import {ElementPage} from '@site/src/components/Elements/ElementPage';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';++# Background Timed Captions++<ElementPage definition={elementDefinitions['text/timed-captions-background']} sourceFile="./timed-captions-background.tsx" />diff --git a/packages/docs/elements/text/timed-captions/timed-captions.tsx b/packages/docs/elements/text/timed-captions-background/timed-captions-background.tsxsimilarity index 70%rename from packages/docs/elements/text/timed-captions/timed-captions.tsxrename to packages/docs/elements/text/timed-captions-background/timed-captions-background.tsxindex 0ec1a398e2..85fe637c88 100644--- a/packages/docs/elements/text/timed-captions/timed-captions.tsx+++ b/packages/docs/elements/text/timed-captions-background/timed-captions-background.tsx@@ -17,26 +17,26 @@ import {interpolate,Sequence,spring,+ useCurrentFrame,+ useVideoConfig,type InteractiveBaseProps,type InteractiveTransformProps,type InteractivitySchema,type SequenceControls,type SequenceProps,- useCurrentFrame,- useVideoConfig,} from 'remotion';-export type TimedCaptionsMode = 'highlight' | 'scale' | 'background';--export type TimedCaptionsProps = InteractiveBaseProps &+type TimedCaptionsBackgroundProps = InteractiveBaseProps &InteractiveTransformProps &Pick<SequenceProps, 'width' | 'height'> & {readonly captions?: Caption[];- readonly mode?: TimedCaptionsMode;readonly combineTokensWithinMilliseconds?: number;};-type TimedCaptionsLayerProps = Omit<TimedCaptionsProps, 'captions'> & {+type TimedCaptionsBackgroundLayerProps = Omit<+ TimedCaptionsBackgroundProps,+ 'captions'+> & {readonly captions: Caption[];};@@ -44,16 +44,14 @@ const desiredFontSize = 80;const maximumTextWidth = 800;const fontWeight = '700';const textColor = '#ffffff';-const highlightColor = '#18ff0e';const backgroundColor = '#0b84f3';-const activeWordScale = 1.2;const pillHorizontalPadding = 12;const pillVerticalPadding = 12;const pillBorderRadius = 10;const pillMoveDurationInFrames = 5;const defaultCombineTokensWithinMilliseconds = 800;-const timedCaptionsSchema = {+const timedCaptionsBackgroundSchema = {...Interactive.baseSchema,...Interactive.captionsSchema,width: {@@ -72,16 +70,6 @@ const timedCaptionsSchema = {description: 'Caption area height',hiddenFromList: false,},- mode: {- type: 'enum',- default: 'background',- description: 'Caption animation',- variants: {- highlight: {},- scale: {},- background: {},- },- },combineTokensWithinMilliseconds: {type: 'number',min: 0,@@ -98,16 +86,16 @@ const {fontFamily, waitUntilDone} = loadFont('normal', {subsets: ['latin'],});-export const frameToMilliseconds = (frame: number, fps: number) =>+const frameToMilliseconds = (frame: number, fps: number) =>(frame / fps) * 1000;-export const isTimeWithinHalfOpenInterval = (+const isTimeWithinHalfOpenInterval = (timeMs: number,fromMs: number,toMs: number,) => timeMs >= fromMs && timeMs < toMs;-export const getActivePageIndex = (+const getActivePageIndex = (pages: readonly Pick<TikTokPage, 'startMs' | 'durationMs'>[],timeMs: number,) =>@@ -119,15 +107,7 @@ export const getActivePageIndex = (),);-export const getActiveTokenIndex = (- tokens: readonly Pick<TikTokToken, 'fromMs' | 'toMs'>[],- timeMs: number,-) =>- tokens.findIndex((token) =>- isTimeWithinHalfOpenInterval(timeMs, token.fromMs, token.toMs),- );--export const getLatestStartedTokenIndex = (+const getLatestStartedTokenIndex = (tokens: readonly Pick<TikTokToken, 'fromMs'>[],timeMs: number,) =>@@ -137,41 +117,6 @@ export const getLatestStartedTokenIndex = (-1,);-export const getTokenScale = ({- currentTimeMs,- fps,- token,-}: {- readonly currentTimeMs: number;- readonly fps: number;- readonly token: Pick<TikTokToken, 'fromMs' | 'toMs'>;-}) => {- if (!isTimeWithinHalfOpenInterval(currentTimeMs, token.fromMs, token.toMs)) {- return 1;- }-- const tokenDurationInFrames = ((token.toMs - token.fromMs) / 1000) * fps;- const tokenLocalFrame = ((currentTimeMs - token.fromMs) / 1000) * fps;- const animationDurationInFrames = Math.min(4, tokenDurationInFrames / 2);- const enterProgress = spring({- config: {damping: 200},- durationInFrames: animationDurationInFrames,- fps,- frame: tokenLocalFrame,- });- const exitProgress = interpolate(- tokenLocalFrame,- [tokenDurationInFrames - animationDurationInFrames, tokenDurationInFrames],- [1, 0],- {- extrapolateLeft: 'clamp',- extrapolateRight: 'clamp',- },- );-- return 1 + Math.min(enterProgress, exitProgress) * (activeWordScale - 1);-};-type TokenLayout = {readonly height: number;readonly left: number;@@ -183,10 +128,9 @@ const CaptionPage: React.FC<{readonly captionAreaWidth: number | null;readonly currentTimeMs: number;readonly fps: number;- readonly mode: TimedCaptionsMode;readonly page: TikTokPage;readonly pageIndex: number;-}> = ({captionAreaWidth, currentTimeMs, fps, mode, page, pageIndex}) => {+}> = ({captionAreaWidth, currentTimeMs, fps, page, pageIndex}) => {const fontSize = useMemo(() => {const availableWidth = Math.min(maximumTextWidth,@@ -194,10 +138,7 @@ const CaptionPage: React.FC<{);const maximumTokenWidth = Math.max(1,- Math.min(- availableWidth - pillHorizontalPadding * 2,- availableWidth / activeWordScale,- ),+ availableWidth - pillHorizontalPadding * 2,);const tokenFontSizes = page.tokens.map((token) => token.text.trim())@@ -261,7 +202,6 @@ const CaptionPage: React.FC<{return () => resizeObserver.disconnect();}, [fontSize, page.tokens]);- const activeTokenIndex = getActiveTokenIndex(page.tokens, currentTimeMs);const latestStartedTokenIndex = getLatestStartedTokenIndex(page.tokens,currentTimeMs,@@ -351,9 +291,7 @@ const CaptionPage: React.FC<{width: '100%',}}>- {mode === 'background' &&- hasTokenLayouts &&- latestStartedTokenIndex >= 0 ? (+ {hasTokenLayouts && latestStartedTokenIndex >= 0 ? (<divaria-hidden="true"style={{@@ -368,7 +306,6 @@ const CaptionPage: React.FC<{/>) : null}{page.tokens.map((token, tokenIndex) => {- const isActive = tokenIndex === activeTokenIndex;const visibleText = token.text.trim();const visibleTextIndex = token.text.indexOf(visibleText);const leadingWhitespace = visibleText@@ -388,17 +325,9 @@ const CaptionPage: React.FC<{tokenRefs.current[tokenIndex] = element;}}style={{- color:- mode !== 'background' && isActive- ? highlightColor- : textColor,+ color: textColor,display: 'inline-block',position: 'relative',- scale:- mode === 'scale'- ? getTokenScale({currentTimeMs, fps, token})- : 1,- transformOrigin: 'center bottom',whiteSpace: 'pre',zIndex: 1,}}@@ -414,18 +343,16 @@ const CaptionPage: React.FC<{);};-const TimedCaptionsContent: React.FC<{+const TimedCaptionsBackgroundContent: React.FC<{readonly captionAreaWidth: number | null;readonly captions: Caption[];readonly combineTokensWithinMilliseconds: number;readonly fontLoaded: boolean;- readonly mode: TimedCaptionsMode;}> = ({captionAreaWidth,captions,combineTokensWithinMilliseconds,fontLoaded,- mode,}) => {const frame = useCurrentFrame();const {fps} = useVideoConfig();@@ -451,16 +378,15 @@ const TimedCaptionsContent: React.FC<{captionAreaWidth={captionAreaWidth}currentTimeMs={currentTimeMs}fps={fps}- mode={mode}page={page}pageIndex={activePageIndex}/>);};-const TimedCaptionsInner = forwardRef<+const TimedCaptionsBackgroundInner = forwardRef<HTMLDivElement,- TimedCaptionsLayerProps & {+ TimedCaptionsBackgroundLayerProps & {readonly controls: SequenceControls | undefined;}>(@@ -470,7 +396,6 @@ const TimedCaptionsInner = forwardRef<combineTokensWithinMilliseconds = defaultCombineTokensWithinMilliseconds,controls,height,- mode = 'background',name,style,width,@@ -500,7 +425,7 @@ const TimedCaptionsInner = forwardRef<layout="none"{...interactiveProps}controls={controls}- name={name ?? '<TimedCaptions>'}+ name={name ?? '<TimedCaptionsBackground>'}outlineRef={outlineRef}><div@@ -511,12 +436,11 @@ const TimedCaptionsInner = forwardRef<...style,}}>- <TimedCaptionsContent+ <TimedCaptionsBackgroundContentcaptionAreaWidth={width ?? null}captions={captions}combineTokensWithinMilliseconds={combineTokensWithinMilliseconds}fontLoaded={fontLoaded}- mode={mode}/></div></Sequence>@@ -524,81 +448,87 @@ const TimedCaptionsInner = forwardRef<},);-const TimedCaptionsLayer = Interactive.withSchema({- Component: TimedCaptionsInner,- componentName: '<TimedCaptions>',+const TimedCaptionsBackgroundLayer = Interactive.withSchema({+ Component: TimedCaptionsBackgroundInner,+ componentName: '<TimedCaptionsBackground>',componentIdentity: null,- schema: timedCaptionsSchema,+ schema: timedCaptionsBackgroundSchema,supportsEffects: false,-}) as React.FC<TimedCaptionsLayerProps>;+}) as React.FC<TimedCaptionsBackgroundLayerProps>;-export const TimedCaptions: React.FC<TimedCaptionsProps> = ({- captions,- ...props-}) => {+export const TimedCaptionsBackground: React.FC<+ TimedCaptionsBackgroundProps+> = ({captions, ...props}) => {if (captions) {- return <TimedCaptionsLayer {...props} captions={captions} />;+ return <TimedCaptionsBackgroundLayer {...props} captions={captions} />;}return (- <TimedCaptionsLayer- {...props}- captions={[- {- text: 'Captions',- startMs: 0,- endMs: 800,- timestampMs: 400,- confidence: null,- },- {- text: ' can',- startMs: 800,- endMs: 1500,- timestampMs: 1150,- confidence: null,- },- {- text: ' move',- startMs: 1500,- endMs: 2300,- timestampMs: 1900,- confidence: null,- },- {- text: ' with',- startMs: 2300,- endMs: 3100,- timestampMs: 2700,- confidence: null,- },- {- text: ' every',- startMs: 3100,- endMs: 4000,- timestampMs: 3550,- confidence: null,- },- {- text: ' spoken',- startMs: 4000,- endMs: 5100,- timestampMs: 4550,- confidence: null,- },- {- text: ' word.',- startMs: 5100,- endMs: 6500,- timestampMs: 5800,- confidence: null,- },- ]}- width={681}- height={252}+ <divstyle={{- translate: '109.5px -36px',+ alignItems: 'center',+ display: 'flex',+ height: 180,+ justifyContent: 'center',+ width: 900,}}- />+ >+ <TimedCaptionsBackgroundLayer+ {...props}+ captions={[+ {+ text: 'Captions',+ startMs: 0,+ endMs: 800,+ timestampMs: 400,+ confidence: null,+ },+ {+ text: ' can',+ startMs: 800,+ endMs: 1500,+ timestampMs: 1150,+ confidence: null,+ },+ {+ text: ' move',+ startMs: 1500,+ endMs: 2300,+ timestampMs: 1900,+ confidence: null,+ },+ {+ text: ' with',+ startMs: 2300,+ endMs: 3100,+ timestampMs: 2700,+ confidence: null,+ },+ {+ text: ' every',+ startMs: 3100,+ endMs: 4000,+ timestampMs: 3550,+ confidence: null,+ },+ {+ text: ' spoken',+ startMs: 4000,+ endMs: 5100,+ timestampMs: 4550,+ confidence: null,+ },+ {+ text: ' word.',+ startMs: 5100,+ endMs: 6500,+ timestampMs: 5800,+ confidence: null,+ },+ ]}+ width={681}+ height={252}+ />+ </div>);};diff --git a/packages/docs/elements/text/timed-captions-highlight/index.mdx b/packages/docs/elements/text/timed-captions-highlight/index.mdxnew file mode 100644index 0000000000..93a39b4f4e--- /dev/null+++ b/packages/docs/elements/text/timed-captions-highlight/index.mdx@@ -0,0 +1,12 @@+---+title: Highlight Timed Captions+description: Animated captions with word-level highlight styling.+image: https://remotion.media/elements/text-timed-captions-highlight-preview.png+---++import {ElementPage} from '@site/src/components/Elements/ElementPage';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';++# Highlight Timed Captions++<ElementPage definition={elementDefinitions['text/timed-captions-highlight']} sourceFile="./timed-captions-highlight.tsx" />diff --git a/packages/docs/elements/text/timed-captions-highlight/timed-captions-highlight.tsx b/packages/docs/elements/text/timed-captions-highlight/timed-captions-highlight.tsxnew file mode 100644index 0000000000..84f9ce433d--- /dev/null+++ b/packages/docs/elements/text/timed-captions-highlight/timed-captions-highlight.tsx@@ -0,0 +1,403 @@+import type {Caption, TikTokPage, TikTokToken} from '@remotion/captions';+import {createTikTokStyleCaptions} from '@remotion/captions';+import {loadFont} from '@remotion/google-fonts/Montserrat';+import {fitText} from '@remotion/layout-utils';+import React, {+ forwardRef,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+} from 'react';+import {+ cancelRender,+ Interactive,+ Sequence,+ useCurrentFrame,+ useVideoConfig,+ type InteractiveBaseProps,+ type InteractiveTransformProps,+ type InteractivitySchema,+ type SequenceControls,+ type SequenceProps,+} from 'remotion';++type TimedCaptionsHighlightProps = InteractiveBaseProps &+ InteractiveTransformProps &+ Pick<SequenceProps, 'width' | 'height'> & {+ readonly captions?: Caption[];+ readonly combineTokensWithinMilliseconds?: number;+ };++type TimedCaptionsHighlightLayerProps = Omit<+ TimedCaptionsHighlightProps,+ 'captions'+> & {+ readonly captions: Caption[];+};++const desiredFontSize = 80;+const maximumTextWidth = 800;+const fontWeight = '700';+const textColor = '#ffffff';+const highlightColor = '#18ff0e';+const defaultCombineTokensWithinMilliseconds = 800;++const timedCaptionsHighlightSchema = {+ ...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: defaultCombineTokensWithinMilliseconds,+ description: 'Time between caption pages',+ hiddenFromList: false,+ },+ ...Interactive.transformSchema,+} as const satisfies InteractivitySchema;++const {fontFamily, waitUntilDone} = loadFont('normal', {+ weights: [fontWeight],+ subsets: ['latin'],+});++const frameToMilliseconds = (frame: number, fps: number) =>+ (frame / fps) * 1000;++const isTimeWithinHalfOpenInterval = (+ timeMs: number,+ fromMs: number,+ toMs: number,+) => timeMs >= fromMs && timeMs < toMs;++const getActivePageIndex = (+ pages: readonly Pick<TikTokPage, 'startMs' | 'durationMs'>[],+ timeMs: number,+) =>+ pages.findIndex((page) =>+ isTimeWithinHalfOpenInterval(+ timeMs,+ page.startMs,+ page.startMs + page.durationMs,+ ),+ );++const getActiveTokenIndex = (+ tokens: readonly Pick<TikTokToken, 'fromMs' | 'toMs'>[],+ timeMs: number,+) =>+ tokens.findIndex((token) =>+ isTimeWithinHalfOpenInterval(timeMs, token.fromMs, token.toMs),+ );++const CaptionPage: React.FC<{+ readonly captionAreaWidth: number | null;+ readonly currentTimeMs: number;+ readonly page: TikTokPage;+ readonly pageIndex: number;+}> = ({captionAreaWidth, currentTimeMs, page, pageIndex}) => {+ const fontSize = useMemo(() => {+ const availableWidth = Math.min(+ maximumTextWidth,+ captionAreaWidth ?? maximumTextWidth,+ );+ const maximumTokenWidth = Math.max(1, availableWidth);+ const tokenFontSizes = page.tokens+ .map((token) => token.text.trim())+ .filter(Boolean)+ .map(+ (text) =>+ fitText({+ fontFamily,+ fontWeight,+ text,+ validateFontIsLoaded: true,+ withinWidth: maximumTokenWidth,+ }).fontSize,+ );++ return Math.min(+ desiredFontSize,+ fitText({+ fontFamily,+ fontWeight,+ text: page.text,+ validateFontIsLoaded: true,+ withinWidth: maximumTextWidth,+ }).fontSize,+ ...tokenFontSizes,+ );+ }, [captionAreaWidth, page.text, page.tokens]);+ const activeTokenIndex = getActiveTokenIndex(page.tokens, currentTimeMs);+ const textStrokeWidth = fontSize / 7;++ return (+ <div+ aria-label={page.text}+ aria-live="off"+ role="group"+ style={{+ alignItems: 'center',+ display: 'flex',+ height: '100%',+ justifyContent: 'center',+ width: '100%',+ }}+ >+ <div+ aria-hidden="true"+ style={{+ color: textColor,+ fontFamily,+ fontSize,+ fontWeight,+ lineHeight: 1.5,+ maxWidth: maximumTextWidth,+ paintOrder: 'stroke fill',+ textAlign: 'center',+ WebkitTextStroke: `${textStrokeWidth}px #000000`,+ whiteSpace: 'normal',+ width: '100%',+ }}+ >+ {page.tokens.map((token, tokenIndex) => {+ const isActive = tokenIndex === activeTokenIndex;+ const visibleText = token.text.trim();+ const visibleTextIndex = token.text.indexOf(visibleText);+ const leadingWhitespace = visibleText+ ? token.text.slice(0, visibleTextIndex)+ : token.text;+ const trailingWhitespace = visibleText+ ? token.text.slice(visibleTextIndex + visibleText.length)+ : '';++ return (+ <React.Fragment+ key={`${pageIndex}-${page.startMs}-${token.fromMs}-${tokenIndex}`}+ >+ {leadingWhitespace}+ <span+ style={{+ color: isActive ? highlightColor : textColor,+ display: 'inline-block',+ whiteSpace: 'pre',+ }}+ >+ {visibleText}+ </span>+ {trailingWhitespace}+ </React.Fragment>+ );+ })}+ </div>+ </div>+ );+};++const TimedCaptionsHighlightContent: React.FC<{+ readonly captionAreaWidth: number | null;+ readonly captions: Caption[];+ readonly combineTokensWithinMilliseconds: number;+ readonly fontLoaded: boolean;+}> = ({+ captionAreaWidth,+ captions,+ combineTokensWithinMilliseconds,+ fontLoaded,+}) => {+ const frame = useCurrentFrame();+ const {fps} = useVideoConfig();+ const pages = useMemo(+ () =>+ createTikTokStyleCaptions({+ captions,+ combineTokensWithinMilliseconds,+ }).pages,+ [captions, combineTokensWithinMilliseconds],+ );+ const currentTimeMs = frameToMilliseconds(frame, fps);+ const activePageIndex = getActivePageIndex(pages, currentTimeMs);+ const page = pages[activePageIndex];++ if (!fontLoaded || !page) {+ return null;+ }++ return (+ <CaptionPage+ key={`${activePageIndex}-${page.startMs}`}+ captionAreaWidth={captionAreaWidth}+ currentTimeMs={currentTimeMs}+ page={page}+ pageIndex={activePageIndex}+ />+ );+};++const TimedCaptionsHighlightInner = forwardRef<+ HTMLDivElement,+ TimedCaptionsHighlightLayerProps & {+ readonly controls: SequenceControls | undefined;+ }+>(+ (+ {+ captions,+ combineTokensWithinMilliseconds = defaultCombineTokensWithinMilliseconds,+ controls,+ height,+ name,+ style,+ width,+ ...interactiveProps+ },+ ref,+ ) => {+ const outlineRef = useRef<HTMLDivElement>(null);+ const [fontLoaded, setFontLoaded] = useState(false);++ useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);++ useEffect(() => {+ waitUntilDone()+ .then(() => {+ setFontLoaded(true);+ })+ .catch((error) => {+ cancelRender(+ error instanceof Error ? error : new Error(String(error)),+ );+ });+ }, []);++ return (+ <Sequence+ layout="none"+ {...interactiveProps}+ controls={controls}+ name={name ?? '<TimedCaptionsHighlight>'}+ outlineRef={outlineRef}+ >+ <div+ ref={outlineRef}+ style={{+ height: height ?? '100%',+ width: width ?? '100%',+ ...style,+ }}+ >+ <TimedCaptionsHighlightContent+ captionAreaWidth={width ?? null}+ captions={captions}+ combineTokensWithinMilliseconds={combineTokensWithinMilliseconds}+ fontLoaded={fontLoaded}+ />+ </div>+ </Sequence>+ );+ },+);++const TimedCaptionsHighlightLayer = Interactive.withSchema({+ Component: TimedCaptionsHighlightInner,+ componentName: '<TimedCaptionsHighlight>',+ componentIdentity: null,+ schema: timedCaptionsHighlightSchema,+ supportsEffects: false,+}) as React.FC<TimedCaptionsHighlightLayerProps>;++export const TimedCaptionsHighlight: React.FC<TimedCaptionsHighlightProps> = ({+ captions,+ ...props+}) => {+ if (captions) {+ return <TimedCaptionsHighlightLayer {...props} captions={captions} />;+ }++ return (+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ height: 180,+ justifyContent: 'center',+ width: 900,+ }}+ >+ <TimedCaptionsHighlightLayer+ {...props}+ captions={[+ {+ text: 'Captions',+ startMs: 0,+ endMs: 800,+ timestampMs: 400,+ confidence: null,+ },+ {+ text: ' can',+ startMs: 800,+ endMs: 1500,+ timestampMs: 1150,+ confidence: null,+ },+ {+ text: ' move',+ startMs: 1500,+ endMs: 2300,+ timestampMs: 1900,+ confidence: null,+ },+ {+ text: ' with',+ startMs: 2300,+ endMs: 3100,+ timestampMs: 2700,+ confidence: null,+ },+ {+ text: ' every',+ startMs: 3100,+ endMs: 4000,+ timestampMs: 3550,+ confidence: null,+ },+ {+ text: ' spoken',+ startMs: 4000,+ endMs: 5100,+ timestampMs: 4550,+ confidence: null,+ },+ {+ text: ' word.',+ startMs: 5100,+ endMs: 6500,+ timestampMs: 5800,+ confidence: null,+ },+ ]}+ width={681}+ height={252}+ />+ </div>+ );+};diff --git a/packages/docs/elements/text/timed-captions-scale/index.mdx b/packages/docs/elements/text/timed-captions-scale/index.mdxnew file mode 100644index 0000000000..71c53f96d7--- /dev/null+++ b/packages/docs/elements/text/timed-captions-scale/index.mdx@@ -0,0 +1,12 @@+---+title: Scale Timed Captions+description: Animated captions with word-level scale styling.+image: https://remotion.media/elements/text-timed-captions-scale-preview.png+---++import {ElementPage} from '@site/src/components/Elements/ElementPage';+import {elementDefinitions} from '@site/src/components/Elements/element-definitions';++# Scale Timed Captions++<ElementPage definition={elementDefinitions['text/timed-captions-scale']} sourceFile="./timed-captions-scale.tsx" />diff --git a/packages/docs/elements/text/timed-captions-scale/timed-captions-scale.tsx b/packages/docs/elements/text/timed-captions-scale/timed-captions-scale.tsxnew file mode 100644index 0000000000..c65d475b24--- /dev/null+++ b/packages/docs/elements/text/timed-captions-scale/timed-captions-scale.tsx@@ -0,0 +1,445 @@+import type {Caption, TikTokPage, TikTokToken} from '@remotion/captions';+import {createTikTokStyleCaptions} from '@remotion/captions';+import {loadFont} from '@remotion/google-fonts/Montserrat';+import {fitText} from '@remotion/layout-utils';+import React, {+ forwardRef,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+} from 'react';+import {+ cancelRender,+ Interactive,+ interpolate,+ Sequence,+ spring,+ useCurrentFrame,+ useVideoConfig,+ type InteractiveBaseProps,+ type InteractiveTransformProps,+ type InteractivitySchema,+ type SequenceControls,+ type SequenceProps,+} from 'remotion';++type TimedCaptionsScaleProps = InteractiveBaseProps &+ InteractiveTransformProps &+ Pick<SequenceProps, 'width' | 'height'> & {+ readonly captions?: Caption[];+ readonly combineTokensWithinMilliseconds?: number;+ };++type TimedCaptionsScaleLayerProps = Omit<+ TimedCaptionsScaleProps,+ 'captions'+> & {+ readonly captions: Caption[];+};++const desiredFontSize = 80;+const maximumTextWidth = 800;+const fontWeight = '700';+const textColor = '#ffffff';+const highlightColor = '#18ff0e';+const activeWordScale = 1.03;+const defaultCombineTokensWithinMilliseconds = 800;++const timedCaptionsScaleSchema = {+ ...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: defaultCombineTokensWithinMilliseconds,+ description: 'Time between caption pages',+ hiddenFromList: false,+ },+ ...Interactive.transformSchema,+} as const satisfies InteractivitySchema;++const {fontFamily, waitUntilDone} = loadFont('normal', {+ weights: [fontWeight],+ subsets: ['latin'],+});++const frameToMilliseconds = (frame: number, fps: number) =>+ (frame / fps) * 1000;++const isTimeWithinHalfOpenInterval = (+ timeMs: number,+ fromMs: number,+ toMs: number,+) => timeMs >= fromMs && timeMs < toMs;++const getActivePageIndex = (+ pages: readonly Pick<TikTokPage, 'startMs' | 'durationMs'>[],+ timeMs: number,+) =>+ pages.findIndex((page) =>+ isTimeWithinHalfOpenInterval(+ timeMs,+ page.startMs,+ page.startMs + page.durationMs,+ ),+ );++const getActiveTokenIndex = (+ tokens: readonly Pick<TikTokToken, 'fromMs' | 'toMs'>[],+ timeMs: number,+) =>+ tokens.findIndex((token) =>+ isTimeWithinHalfOpenInterval(timeMs, token.fromMs, token.toMs),+ );++const getTokenScale = ({+ currentTimeMs,+ fps,+ token,+}: {+ readonly currentTimeMs: number;+ readonly fps: number;+ readonly token: Pick<TikTokToken, 'fromMs' | 'toMs'>;+}) => {+ if (!isTimeWithinHalfOpenInterval(currentTimeMs, token.fromMs, token.toMs)) {+ return 1;+ }++ const tokenDurationInFrames = ((token.toMs - token.fromMs) / 1000) * fps;+ const tokenLocalFrame = ((currentTimeMs - token.fromMs) / 1000) * fps;+ const animationDurationInFrames = Math.min(4, tokenDurationInFrames / 2);+ const enterProgress = spring({+ config: {damping: 200},+ durationInFrames: animationDurationInFrames,+ fps,+ frame: tokenLocalFrame,+ });+ const exitProgress = interpolate(+ tokenLocalFrame,+ [tokenDurationInFrames - animationDurationInFrames, tokenDurationInFrames],+ [1, 0],+ {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ },+ );++ return 1 + Math.min(enterProgress, exitProgress) * (activeWordScale - 1);+};++const CaptionPage: React.FC<{+ readonly captionAreaWidth: number | null;+ readonly currentTimeMs: number;+ readonly fps: number;+ readonly page: TikTokPage;+ readonly pageIndex: number;+}> = ({captionAreaWidth, currentTimeMs, fps, page, pageIndex}) => {+ const fontSize = useMemo(() => {+ const availableWidth = Math.min(+ maximumTextWidth,+ captionAreaWidth ?? maximumTextWidth,+ );+ const maximumTokenWidth = Math.max(1, availableWidth / activeWordScale);+ const tokenFontSizes = page.tokens+ .map((token) => token.text.trim())+ .filter(Boolean)+ .map(+ (text) =>+ fitText({+ fontFamily,+ fontWeight,+ text,+ validateFontIsLoaded: true,+ withinWidth: maximumTokenWidth,+ }).fontSize,+ );++ return Math.min(+ desiredFontSize,+ fitText({+ fontFamily,+ fontWeight,+ text: page.text,+ validateFontIsLoaded: true,+ withinWidth: maximumTextWidth,+ }).fontSize,+ ...tokenFontSizes,+ );+ }, [captionAreaWidth, page.text, page.tokens]);+ const activeTokenIndex = getActiveTokenIndex(page.tokens, currentTimeMs);+ const textStrokeWidth = fontSize / 7;++ return (+ <div+ aria-label={page.text}+ aria-live="off"+ role="group"+ style={{+ alignItems: 'center',+ display: 'flex',+ height: '100%',+ justifyContent: 'center',+ width: '100%',+ }}+ >+ <div+ aria-hidden="true"+ style={{+ color: textColor,+ fontFamily,+ fontSize,+ fontWeight,+ lineHeight: 1.5,+ maxWidth: maximumTextWidth,+ paintOrder: 'stroke fill',+ textAlign: 'center',+ WebkitTextStroke: `${textStrokeWidth}px #000000`,+ whiteSpace: 'normal',+ width: '100%',+ }}+ >+ {page.tokens.map((token, tokenIndex) => {+ const isActive = tokenIndex === activeTokenIndex;+ const visibleText = token.text.trim();+ const visibleTextIndex = token.text.indexOf(visibleText);+ const leadingWhitespace = visibleText+ ? token.text.slice(0, visibleTextIndex)+ : token.text;+ const trailingWhitespace = visibleText+ ? token.text.slice(visibleTextIndex + visibleText.length)+ : '';++ return (+ <React.Fragment+ key={`${pageIndex}-${page.startMs}-${token.fromMs}-${tokenIndex}`}+ >+ {leadingWhitespace}+ <span+ style={{+ color: isActive ? highlightColor : textColor,+ display: 'inline-block',+ scale: getTokenScale({currentTimeMs, fps, token}),+ transformOrigin: 'center bottom',+ whiteSpace: 'pre',+ }}+ >+ {visibleText}+ </span>+ {trailingWhitespace}+ </React.Fragment>+ );+ })}+ </div>+ </div>+ );+};++const TimedCaptionsScaleContent: React.FC<{+ readonly captionAreaWidth: number | null;+ readonly captions: Caption[];+ readonly combineTokensWithinMilliseconds: number;+ readonly fontLoaded: boolean;+}> = ({+ captionAreaWidth,+ captions,+ combineTokensWithinMilliseconds,+ fontLoaded,+}) => {+ const frame = useCurrentFrame();+ const {fps} = useVideoConfig();+ const pages = useMemo(+ () =>+ createTikTokStyleCaptions({+ captions,+ combineTokensWithinMilliseconds,+ }).pages,+ [captions, combineTokensWithinMilliseconds],+ );+ const currentTimeMs = frameToMilliseconds(frame, fps);+ const activePageIndex = getActivePageIndex(pages, currentTimeMs);+ const page = pages[activePageIndex];++ if (!fontLoaded || !page) {+ return null;+ }++ return (+ <CaptionPage+ key={`${activePageIndex}-${page.startMs}`}+ captionAreaWidth={captionAreaWidth}+ currentTimeMs={currentTimeMs}+ fps={fps}+ page={page}+ pageIndex={activePageIndex}+ />+ );+};++const TimedCaptionsScaleInner = forwardRef<+ HTMLDivElement,+ TimedCaptionsScaleLayerProps & {+ readonly controls: SequenceControls | undefined;+ }+>(+ (+ {+ captions,+ combineTokensWithinMilliseconds = defaultCombineTokensWithinMilliseconds,+ controls,+ height,+ name,+ style,+ width,+ ...interactiveProps+ },+ ref,+ ) => {+ const outlineRef = useRef<HTMLDivElement>(null);+ const [fontLoaded, setFontLoaded] = useState(false);++ useImperativeHandle(ref, () => outlineRef.current as HTMLDivElement, []);++ useEffect(() => {+ waitUntilDone()+ .then(() => {+ setFontLoaded(true);+ })+ .catch((error) => {+ cancelRender(+ error instanceof Error ? error : new Error(String(error)),+ );+ });+ }, []);++ return (+ <Sequence+ layout="none"+ {...interactiveProps}+ controls={controls}+ name={name ?? '<TimedCaptionsScale>'}+ outlineRef={outlineRef}+ >+ <div+ ref={outlineRef}+ style={{+ height: height ?? '100%',+ width: width ?? '100%',+ ...style,+ }}+ >+ <TimedCaptionsScaleContent+ captionAreaWidth={width ?? null}+ captions={captions}+ combineTokensWithinMilliseconds={combineTokensWithinMilliseconds}+ fontLoaded={fontLoaded}+ />+ </div>+ </Sequence>+ );+ },+);++const TimedCaptionsScaleLayer = Interactive.withSchema({+ Component: TimedCaptionsScaleInner,+ componentName: '<TimedCaptionsScale>',+ componentIdentity: null,+ schema: timedCaptionsScaleSchema,+ supportsEffects: false,+}) as React.FC<TimedCaptionsScaleLayerProps>;++export const TimedCaptionsScale: React.FC<TimedCaptionsScaleProps> = ({+ captions,+ ...props+}) => {+ if (captions) {+ return <TimedCaptionsScaleLayer {...props} captions={captions} />;+ }++ return (+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ height: 180,+ justifyContent: 'center',+ width: 900,+ }}+ >+ <TimedCaptionsScaleLayer+ {...props}+ captions={[+ {+ text: 'Captions',+ startMs: 0,+ endMs: 800,+ timestampMs: 400,+ confidence: null,+ },+ {+ text: ' can',+ startMs: 800,+ endMs: 1500,+ timestampMs: 1150,+ confidence: null,+ },+ {+ text: ' move',+ startMs: 1500,+ endMs: 2300,+ timestampMs: 1900,+ confidence: null,+ },+ {+ text: ' with',+ startMs: 2300,+ endMs: 3100,+ timestampMs: 2700,+ confidence: null,+ },+ {+ text: ' every',+ startMs: 3100,+ endMs: 4000,+ timestampMs: 3550,+ confidence: null,+ },+ {+ text: ' spoken',+ startMs: 4000,+ endMs: 5100,+ timestampMs: 4550,+ confidence: null,+ },+ {+ text: ' word.',+ startMs: 5100,+ endMs: 6500,+ timestampMs: 5800,+ confidence: null,+ },+ ]}+ width={681}+ height={252}+ />+ </div>+ );+};diff --git a/packages/docs/elements/text/timed-captions/index.mdx b/packages/docs/elements/text/timed-captions/index.mdxdeleted file mode 100644index 07ca981a25..0000000000--- a/packages/docs/elements/text/timed-captions/index.mdx+++ /dev/null@@ -1,12 +0,0 @@-----title: Timed Captions-description: Animated captions with word-level highlighting, scaling, or a moving background.-image: https://remotion.media/elements/text-timed-captions-preview.png------import {ElementPage} from '@site/src/components/Elements/ElementPage';-import {elementDefinitions} from '@site/src/components/Elements/element-definitions';--# Timed Captions--<ElementPage definition={elementDefinitions['text/timed-captions']} sourceFile="./timed-captions.tsx" />diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.tsindex 59e1652eb9..d0b7598998 100644--- a/packages/docs/src/components/Elements/element-definitions.ts+++ b/packages/docs/src/components/Elements/element-definitions.ts@@ -14,7 +14,9 @@ import {CrossedOffText} from '../../../elements/text/crossed-off/crossed-off';import {NewsArticleHeadlineHighlight} from '../../../elements/text/news-article-headline-highlight/news-article-headline-highlight';import {StrikeThroughText} from '../../../elements/text/strike-through/strike-through';import {TextMarker} from '../../../elements/text/text-marker/text-marker';-import {TimedCaptions} from '../../../elements/text/timed-captions/timed-captions';+import {TimedCaptionsBackground} from '../../../elements/text/timed-captions-background/timed-captions-background';+import {TimedCaptionsHighlight} from '../../../elements/text/timed-captions-highlight/timed-captions-highlight';+import {TimedCaptionsScale} from '../../../elements/text/timed-captions-scale/timed-captions-scale';import type {Contributor} from '../Credits';export type ElementPreviewMetadata = {@@ -388,18 +390,71 @@ export const elementDefinitions = {slug: 'text/text-marker',width: 1920,},- 'text/timed-captions': {+ 'text/timed-captions-background': {category: 'text',- component: TimedCaptions,+ component: TimedCaptionsBackground,contributors: [{username: 'JonnyBurger', contribution: null}],- description:- 'Previously a paid template on remotion.pro, Timed Captions is now free for everyone.',+ description: 'Animated captions with word-level moving background styling.',+ dependencies: [+ {name: '@remotion/captions', version: null},+ {name: '@remotion/google-fonts', version: null},+ {name: '@remotion/layout-utils', version: null},+ ],+ displayName: 'Background Timed Captions',+ durationInFrames: 210,+ elementHeight: 180,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 75,+ preview: {+ posterUrl:+ 'https://remotion.media/elements/text-timed-captions-background-preview.png',+ videoUrl:+ 'https://remotion.media/elements/text-timed-captions-background-preview.mp4',+ },+ previewPadding: 120,+ slug: 'text/timed-captions-background',+ width: 1920,+ },+ 'text/timed-captions-highlight': {+ category: 'text',+ component: TimedCaptionsHighlight,+ contributors: [{username: 'JonnyBurger', contribution: null}],+ description: 'Animated captions with word-level highlight styling.',+ dependencies: [+ {name: '@remotion/captions', version: null},+ {name: '@remotion/google-fonts', version: null},+ {name: '@remotion/layout-utils', version: null},+ ],+ displayName: 'Highlight Timed Captions',+ durationInFrames: 210,+ elementHeight: 180,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 75,+ preview: {+ posterUrl:+ 'https://remotion.media/elements/text-timed-captions-highlight-preview.png',+ videoUrl:+ 'https://remotion.media/elements/text-timed-captions-highlight-preview.mp4',+ },+ previewPadding: 120,+ slug: 'text/timed-captions-highlight',+ width: 1920,+ },+ 'text/timed-captions-scale': {+ category: 'text',+ component: TimedCaptionsScale,+ contributors: [{username: 'JonnyBurger', contribution: null}],+ description: 'Animated captions with word-level scale styling.',dependencies: [{name: '@remotion/captions', version: null},{name: '@remotion/google-fonts', version: null},{name: '@remotion/layout-utils', version: null},],- displayName: 'Timed Captions',+ displayName: 'Scale Timed Captions',durationInFrames: 210,elementHeight: 180,elementWidth: 900,@@ -408,12 +463,12 @@ export const elementDefinitions = {posterFrame: 75,preview: {posterUrl:- 'https://remotion.media/elements/text-timed-captions-preview.png',+ 'https://remotion.media/elements/text-timed-captions-scale-preview.png',videoUrl:- 'https://remotion.media/elements/text-timed-captions-preview.mp4',+ 'https://remotion.media/elements/text-timed-captions-scale-preview.mp4',},previewPadding: 120,- slug: 'text/timed-captions',+ slug: 'text/timed-captions-scale',width: 1920,},} satisfies Record<string, ElementDefinition>;diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.tsindex 343e33d5c2..e7a66b96a4 100644--- a/packages/docs/src/test/elements.test.ts+++ b/packages/docs/src/test/elements.test.ts@@ -258,34 +258,35 @@ describe('Element social previews', () => {}});- test('renders Open Graph video metadata for the published preview', () => {- const markup = renderToStaticMarkup(- React.createElement(- React.Fragment,- null,- ...Seo.renderVideo({- height: 420,- url: 'https://remotion.media/elements/text-timed-captions-preview.mp4',- width: 1140,- }),- ),- );+ test('renders Open Graph video metadata for published previews', () => {+ for (const definition of elementDefinitionList) {+ const url = definition.preview.videoUrl;+ const markup = renderToStaticMarkup(+ React.createElement(+ React.Fragment,+ null,+ ...Seo.renderVideo({+ height: 420,+ url,+ width: 1140,+ }),+ ),+ );- expect(markup).toContain(- '<meta property="og:video" content="https://remotion.media/elements/text-timed-captions-preview.mp4"/>',- );- expect(markup).toContain(- '<meta property="og:video:secure_url" content="https://remotion.media/elements/text-timed-captions-preview.mp4"/>',- );- expect(markup).toContain(- '<meta property="og:video:type" content="video/mp4"/>',- );- expect(markup).toContain(- '<meta property="og:video:width" content="1140"/>',- );- expect(markup).toContain(- '<meta property="og:video:height" content="420"/>',- );+ expect(markup).toContain(`<meta property="og:video" content="${url}"/>`);+ expect(markup).toContain(+ `<meta property="og:video:secure_url" content="${url}"/>`,+ );+ expect(markup).toContain(+ '<meta property="og:video:type" content="video/mp4"/>',+ );+ expect(markup).toContain(+ '<meta property="og:video:width" content="1140"/>',+ );+ expect(markup).toContain(+ '<meta property="og:video:height" content="420"/>',+ );+ }});});@@ -308,6 +309,31 @@ describe('Element preview definitions', () => {}});+ test('publishes timed caption styles as separate Elements', () => {+ const timedCaptionSlugs = elementDefinitionList+ .map((definition) => definition.slug)+ .filter((slug) => slug.startsWith('text/timed-captions'))+ .sort();++ expect(timedCaptionSlugs).toEqual([+ 'text/timed-captions-background',+ 'text/timed-captions-highlight',+ 'text/timed-captions-scale',+ ]);++ for (const slug of timedCaptionSlugs) {+ const element = productionElements.find((entry) => entry.name === slug);+ if (!element) {+ throw new Error(`Missing timed caption Element for ${slug}`);+ }++ const source = readFileSync(element.tsxPath, 'utf8');+ expect(source).not.toContain('readonly mode');+ expect(source).not.toContain('TimedCaptionsMode');+ expect(source).not.toContain("translate: '109.5px -36px'");+ }+ });+test('declares every external source dependency centrally', () => {for (const element of productionElements) {const definition = elementDefinitionList.find(