🎥 Make videos programmatically with React
Elements: Add rounded captions
Jonny Burgere51c4aa7d1ed
diff --git a/packages/docs/elements/captions/rounded-captions/index.mdx b/packages/docs/elements/captions/rounded-captions/index.mdxnew file mode 100644index 0000000000..b5a50fbe54--- /dev/null+++ b/packages/docs/elements/captions/rounded-captions/index.mdx@@ -0,0 +1,15 @@+---+title: Rounded Captions+sidebar_label: Rounded+description: Static synchronized captions with a rounded background that follows each line.+image: https://remotion.media/elements/captions-rounded-captions-preview-694426c4-721c-484f-8a33-79f21d54da5d.png+---++import {ElementPage} from '@site/src/components/Elements/ElementPage';+import {getElementDefinition} from '@site/src/components/Elements/element-utils';++# Rounded Captions++Based on the [`@remotion/rounded-text-box` demo](/docs/rounded-text-box/create-rounded-text-box).++<ElementPage definition={getElementDefinition('captions/rounded-captions')} sourceFile="./rounded-captions.tsx" />diff --git a/packages/docs/elements/captions/rounded-captions/initial-props.ts b/packages/docs/elements/captions/rounded-captions/initial-props.tsnew file mode 100644index 0000000000..a911b86604--- /dev/null+++ b/packages/docs/elements/captions/rounded-captions/initial-props.ts@@ -0,0 +1,34 @@+import type {ComponentProps} from 'react';+import type {RoundedCaptions} from './rounded-captions';++export const roundedCaptionsInitialProps = {+ captions: [+ {+ text: 'Rounded captions,\nready for every video.',+ startMs: 0,+ endMs: 2200,+ timestampMs: 1100,+ confidence: null,+ pageBreakAfter: true,+ },+ {+ text: 'Clear text,\nwith a rounded background.',+ startMs: 2200,+ endMs: 4400,+ timestampMs: 3300,+ confidence: null,+ pageBreakAfter: true,+ },+ {+ text: 'Easy to read,\nand easy to customize.',+ startMs: 4400,+ endMs: 7000,+ timestampMs: 5700,+ confidence: null,+ },+ ],+ playbackRate: 1,+ combineTokensWithinMilliseconds: 2000,+ width: 900,+ height: 220,+} satisfies ComponentProps<typeof RoundedCaptions>;diff --git a/packages/docs/elements/captions/rounded-captions/rounded-captions.tsx b/packages/docs/elements/captions/rounded-captions/rounded-captions.tsxnew file mode 100644index 0000000000..38114e8775--- /dev/null+++ b/packages/docs/elements/captions/rounded-captions/rounded-captions.tsx@@ -0,0 +1,291 @@+import type {Caption} from '@remotion/captions';+import {createTikTokStyleCaptions} from '@remotion/captions';+import {loadFont} from '@remotion/google-fonts/Figtree';+import {fitTextOnNLines, measureText} from '@remotion/layout-utils';+import {createRoundedTextBox} from '@remotion/rounded-text-box';+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 RoundedCaptionsProps = InteractiveBaseProps &+ InteractiveTransformProps &+ Pick<SequenceProps, 'width' | 'height'> & {+ readonly captions: Caption[];+ readonly playbackRate: number | null;+ readonly combineTokensWithinMilliseconds: number | null;+ };++const defaultCombineTokensWithinMilliseconds = 2000;+const defaultWidth = 900;+const defaultHeight = 220;+const fontWeight = '700';+const maxFontSize = 64;+const lineHeight = 1.5;+const horizontalPadding = 22;+const borderRadius = 20;++const roundedCaptionsSchema = {+ ...Interactive.baseSchema,+ ...Interactive.captionsSchema,+ width: {+ type: 'number',+ min: horizontalPadding * 2 + 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 RoundedCaptionsContent: React.FC<{+ readonly captions: Caption[];+ readonly playbackRate: number;+ readonly trimBefore: number;+ readonly combineTokensWithinMilliseconds: number;+ readonly fontLoaded: boolean;+ readonly width: number;+ readonly height: number;+}> = ({+ captions,+ playbackRate,+ trimBefore,+ combineTokensWithinMilliseconds,+ fontLoaded,+ width,+ height,+}) => {+ const frame = useCurrentFrame();+ const {fps} = useVideoConfig();+ const pages = useMemo(+ () =>+ createTikTokStyleCaptions({+ captions,+ combineTokensWithinMilliseconds,+ }).pages,+ [captions, combineTokensWithinMilliseconds],+ );+ // The Sequence frame already includes trimBefore; only elapsed frames speed up.+ const currentTimeMs =+ ((trimBefore + (frame - trimBefore) * playbackRate) / fps) * 1000;+ const page = pages.find(+ (candidate) =>+ currentTimeMs >= candidate.startMs &&+ currentTimeMs < candidate.startMs + candidate.durationMs,+ );+ const layout = useMemo(() => {+ if (!fontLoaded || !page?.text.trim()) {+ return null;+ }++ const paragraphs = page.text+ .trim()+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ const maxLines = Math.max(2, paragraphs.length);+ const fitted = paragraphs.map((text) =>+ fitTextOnNLines({+ text,+ maxLines: paragraphs.length === 1 ? maxLines : 1,+ maxBoxWidth: Math.max(1, width - horizontalPadding * 2),+ fontFamily,+ fontWeight,+ maxFontSize: Math.min(maxFontSize, height / (maxLines * lineHeight)),+ validateFontIsLoaded: true,+ }),+ );+ if (fitted.some((result) => result.lines.length === 0)) {+ return null;+ }++ const fontSize = Math.min(...fitted.map((result) => result.fontSize));+ const lines = fitted.flatMap((result) => result.lines);+ const textMeasurements = lines.map((text) =>+ measureText({+ text,+ fontFamily,+ fontSize,+ fontWeight,+ additionalStyles: {lineHeight},+ validateFontIsLoaded: true,+ }),+ );++ return {+ fontSize,+ lines,+ ...createRoundedTextBox({+ textMeasurements,+ textAlign: 'center',+ horizontalPadding,+ borderRadius,+ }),+ };+ }, [fontLoaded, height, page, width]);++ if (!layout) {+ return null;+ }++ return (+ <div+ style={{+ position: 'relative',+ width: layout.boundingBox.width,+ height: layout.boundingBox.height,+ flexShrink: 0,+ }}+ >+ <svg+ viewBox={layout.boundingBox.viewBox}+ style={{+ position: 'absolute',+ left: 0,+ top: 0,+ width: layout.boundingBox.width,+ height: layout.boundingBox.height,+ overflow: 'visible',+ }}+ >+ <path fill="#ffffff" d={layout.d} />+ </svg>+ <div style={{position: 'relative'}}>+ {layout.lines.map((line, index) => (+ <div+ // eslint-disable-next-line react/no-array-index-key+ key={index}+ style={{+ color: '#000000',+ fontFamily,+ fontSize: layout.fontSize,+ fontWeight,+ lineHeight,+ paddingInline: horizontalPadding,+ textAlign: 'center',+ whiteSpace: 'pre',+ }}+ >+ {line}+ </div>+ ))}+ </div>+ </div>+ );+};++const RoundedCaptionsInner = forwardRef<+ HTMLDivElement,+ RoundedCaptionsProps & {+ readonly controls: SequenceControls | undefined;+ }+>(+ (+ {+ captions,+ combineTokensWithinMilliseconds,+ controls,+ height = defaultHeight,+ name,+ playbackRate,+ style,+ trimBefore,+ width = defaultWidth,+ ...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));+ }, []);++ return (+ <Sequence+ layout="none"+ {...interactiveProps}+ controls={controls}+ name={name ?? '<RoundedCaptions>'}+ trimBefore={trimBefore}+ outlineRef={outlineRef}+ >+ <div+ ref={outlineRef}+ style={{+ alignItems: 'center',+ display: 'flex',+ justifyContent: 'center',+ marginInline: 'auto',+ width,+ height,+ ...style,+ }}+ >+ <RoundedCaptionsContent+ captions={captions}+ combineTokensWithinMilliseconds={+ combineTokensWithinMilliseconds ??+ defaultCombineTokensWithinMilliseconds+ }+ fontLoaded={fontLoaded}+ playbackRate={playbackRate ?? 1}+ trimBefore={trimBefore ?? 0}+ width={width}+ height={height}+ />+ </div>+ </Sequence>+ );+ },+);++export const RoundedCaptions = Interactive.withSchema({+ Component: RoundedCaptionsInner,+ componentName: '<RoundedCaptions>',+ schema: roundedCaptionsSchema,+ supportsEffects: false,+}) as React.FC<RoundedCaptionsProps>;diff --git a/packages/docs/src/components/Elements/element-definitions.ts b/packages/docs/src/components/Elements/element-definitions.tsindex 97b199c19d..dff612f925 100644--- a/packages/docs/src/components/Elements/element-definitions.ts+++ b/packages/docs/src/components/Elements/element-definitions.ts@@ -19,6 +19,8 @@ import {movingPillCaptionsInitialProps} from '../../../elements/captions/moving-import {MovingPillCaptions} from '../../../elements/captions/moving-pill-captions/moving-pill-captions';import {poppingWordCaptionsInitialProps} from '../../../elements/captions/popping-word-captions/initial-props';import {PoppingWordCaptions} from '../../../elements/captions/popping-word-captions/popping-word-captions';+import {roundedCaptionsInitialProps} from '../../../elements/captions/rounded-captions/initial-props';+import {RoundedCaptions} from '../../../elements/captions/rounded-captions/rounded-captions';import {wordHighlightCaptionsInitialProps} from '../../../elements/captions/word-highlight-captions/initial-props';import {WordHighlightCaptions} from '../../../elements/captions/word-highlight-captions/word-highlight-captions';import {@@ -348,6 +350,36 @@ const elementImplementations = [installationMode: 'component-owned-sequence',width: 1920,},+ {+ slug: 'captions/rounded-captions',+ component: RoundedCaptions,+ contributors: [{username: 'JonnyBurger', contribution: null}],+ description:+ 'Static synchronized captions with a rounded background that follows each line.',+ dependencies: [+ {name: '@remotion/captions', version: null},+ {name: '@remotion/google-fonts', version: null},+ {name: '@remotion/layout-utils', version: null},+ {name: '@remotion/rounded-text-box', version: null},+ ],+ durationInFrames: 210,+ elementHeight: 220,+ elementWidth: 900,+ fps: 30,+ height: 1080,+ posterFrame: 75,+ preview: {+ previewLayout: 'composition',+ posterUrl:+ 'https://remotion.media/elements/captions-rounded-captions-preview-694426c4-721c-484f-8a33-79f21d54da5d.png',+ videoUrl:+ 'https://remotion.media/elements/captions-rounded-captions-preview-694426c4-721c-484f-8a33-79f21d54da5d.mp4',+ },+ safeArea: 120,+ initialProps: roundedCaptionsInitialProps,+ installationMode: 'component-owned-sequence',+ width: 1920,+ },{slug: 'captions/moving-pill-captions',component: MovingPillCaptions,diff --git a/packages/docs/src/components/Elements/element-registry.ts b/packages/docs/src/components/Elements/element-registry.tsindex ffcc937a8a..71a5db27db 100644--- a/packages/docs/src/components/Elements/element-registry.ts+++ b/packages/docs/src/components/Elements/element-registry.ts@@ -55,6 +55,10 @@ export const elementRegistry = {category: 'captions',displayName: 'Basic Captions',},+ 'captions/rounded-captions': {+ category: 'captions',+ displayName: 'Rounded Captions',+ },'captions/moving-pill-captions': {category: 'captions',displayName: 'Moving Pill Captions',