Skip to content

🎥 Make videos programmatically with React

awesome

Jonny Burgerca9261ccb215
diff --git a/packages/captions/src/create-tiktok-style-captions.ts b/packages/captions/src/create-tiktok-style-captions.ts
index b0543befc3..912a5b8693 100644
--- a/packages/captions/src/create-tiktok-style-captions.ts
+++ b/packages/captions/src/create-tiktok-style-captions.ts
@@ -12,13 +12,19 @@ export type TikTokPage = {
tokens: TikTokToken[];
};
+export type CreateTikTokStyleCaptionsInput = {
+ captions: Caption[];
+ combineTokensWithinMilliseconds: number;
+};
+
+export type CreateTikTokStyleCaptionsOutput = {
+ pages: TikTokPage[];
+};
+
export function createTikTokStyleCaptions({
captions,
combineTokensWithinMilliseconds,
-}: {
- captions: Caption[];
- combineTokensWithinMilliseconds: number;
-}): {pages: TikTokPage[]} {
+}: CreateTikTokStyleCaptionsInput): CreateTikTokStyleCaptionsOutput {
const tikTokStyleCaptions: TikTokPage[] = [];
let currentText = '';
let currentTokens: TikTokToken[] = [];
diff --git a/packages/captions/src/ensure-max-characters-per-line.ts b/packages/captions/src/ensure-max-characters-per-line.ts
new file mode 100644
index 0000000000..987da51f7d
--- /dev/null
+++ b/packages/captions/src/ensure-max-characters-per-line.ts
@@ -0,0 +1,65 @@
+import {Caption} from './caption';
+
+const splitWords = (word: Caption[]): Caption[] => {
+ const captions: Caption[] = [];
+
+ for (let i = 0; i < word.length; i++) {
+ const w = word[i];
+ const words = w.text.split(' ');
+
+ for (let j = 0; j < words.length; j++) {
+ const word = words[j];
+ captions.push({
+ text: j === 0 ? ` ${word}` : word,
+ startMs: w.startMs,
+ endMs: w.endMs,
+ confidence: w.confidence,
+ timestampMs: w.timestampMs,
+ });
+ }
+ }
+
+ return captions;
+};
+
+export type EnsureMaxCharactersPerLineInput = {
+ captions: Caption[];
+ maxCharsPerLine: number;
+};
+
+export type EnsureMaxCharactersPerLineOutput = {segments: Caption[][]};
+
+export const ensureMaxCharactersPerLine = ({
+ captions,
+ maxCharsPerLine,
+}: EnsureMaxCharactersPerLineInput): EnsureMaxCharactersPerLineOutput => {
+ const splitted = splitWords(captions);
+
+ const segments: Caption[][] = [];
+ let currentSegment: Caption[] = [];
+
+ for (let i = 0; i < splitted.length; i++) {
+ const w = splitted[i] as Caption;
+ const remainingWords = splitted.slice(i + 1);
+ const filledCharactersInLine = currentSegment
+ .map((s) => s.text.length)
+ .reduce((a, b) => a + b, 0);
+
+ const preventOrphanWord =
+ remainingWords.length < 4 &&
+ remainingWords.length > 1 &&
+ filledCharactersInLine > maxCharsPerLine / 2;
+
+ if (
+ filledCharactersInLine + w.text.length > maxCharsPerLine ||
+ preventOrphanWord
+ ) {
+ segments.push(currentSegment);
+ currentSegment = [];
+ }
+ currentSegment.push(w);
+ }
+
+ segments.push(currentSegment);
+ return {segments};
+};
diff --git a/packages/captions/src/index.ts b/packages/captions/src/index.ts
index 7c8a3d61f8..2440032140 100644
--- a/packages/captions/src/index.ts
+++ b/packages/captions/src/index.ts
@@ -1,7 +1,20 @@
+import {ensureMaxCharactersPerLine} from './ensure-max-characters-per-line';
+
export {Caption} from './caption';
export {
+ createTikTokStyleCaptions,
+ CreateTikTokStyleCaptionsInput,
+ CreateTikTokStyleCaptionsOutput,
TikTokPage,
TikTokToken,
- createTikTokStyleCaptions,
} from './create-tiktok-style-captions';
-export {parseSrt} from './parse-srt';
+export {
+ EnsureMaxCharactersPerLineInput,
+ EnsureMaxCharactersPerLineOutput,
+} from './ensure-max-characters-per-line';
+export {parseSrt, ParseSrtInput, ParseSrtOutput} from './parse-srt';
+export {serializeSrt, SerializeSrtInput} from './serialize-srt';
+
+export const CaptionsInternals = {
+ ensureMaxCharactersPerLine,
+};
diff --git a/packages/captions/src/serialize-srt.ts b/packages/captions/src/serialize-srt.ts
new file mode 100644
index 0000000000..08f4b122a7
--- /dev/null
+++ b/packages/captions/src/serialize-srt.ts
@@ -0,0 +1,43 @@
+import {Caption} from './caption';
+
+const formatSingleSrtTimestamp = (timestamp: number) => {
+ const hours = Math.floor(timestamp / 3600000);
+ const minutes = Math.floor((timestamp % 3600000) / 60000);
+ const seconds = Math.floor((timestamp % 60000) / 1000);
+ const milliseconds = Math.floor(timestamp % 1000);
+
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')},${String(milliseconds).padStart(3, '0')}`;
+};
+
+const formatSrtTimestamp = (startMs: number, endMs: number) => {
+ return `${formatSingleSrtTimestamp(startMs)} --> ${formatSingleSrtTimestamp(endMs)}`;
+};
+
+export type SerializeSrtInput = {
+ lines: Caption[][];
+};
+
+export const serializeSrt = ({lines}: SerializeSrtInput) => {
+ let currentIndex = 0;
+
+ return lines
+ .map((s) => {
+ currentIndex++;
+ if (s.length === 0) {
+ return null;
+ }
+
+ const firstTimestamp = s[0].startMs;
+ const lastTimestamp = s[s.length - 1].endMs;
+
+ return [
+ // Index
+ currentIndex,
+ formatSrtTimestamp(firstTimestamp, lastTimestamp),
+ // Text
+ s.map((caption) => caption.text).join(''),
+ ].join('\n');
+ })
+ .filter(Boolean)
+ .join('\n\n');
+};
diff --git a/packages/captions/src/test/ensure-max-characters.test.ts b/packages/captions/src/test/ensure-max-characters.test.ts
new file mode 100644
index 0000000000..fe5dba3458
--- /dev/null
+++ b/packages/captions/src/test/ensure-max-characters.test.ts
@@ -0,0 +1,160 @@
+import {expect, test} from 'bun:test';
+import {Caption} from '../caption';
+import {ensureMaxCharactersPerLine} from '../ensure-max-characters-per-line';
+
+test('Ensure max characters per line', () => {
+ const captions: Caption[] = [
+ {
+ confidence: 1,
+ endMs: 6000,
+ startMs: 3000,
+ text: 'This is a demonstration of SRT subtitles.',
+ timestampMs: 4500,
+ },
+ {
+ confidence: 1,
+ endMs: 10500,
+ startMs: 7000,
+ text: 'You can use SRT files to add subtitles to your videos.',
+ timestampMs: 8750,
+ },
+ ];
+
+ // TODO: This creates captions that are not nice!
+ expect(ensureMaxCharactersPerLine({captions, maxCharsPerLine: 42})).toEqual({
+ segments: [
+ [
+ {
+ text: ' This',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: 'is',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: 'a',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: 'demonstration',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: 'of',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: 'SRT',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: 'subtitles.',
+ startMs: 3000,
+ endMs: 6000,
+ confidence: 1,
+ timestampMs: 4500,
+ },
+ {
+ text: ' You',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ ],
+ [
+ {
+ text: 'can',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'use',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'SRT',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'files',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'to',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'add',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'subtitles',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ ],
+ [
+ {
+ text: 'to',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'your',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ {
+ text: 'videos.',
+ startMs: 7000,
+ endMs: 10500,
+ confidence: 1,
+ timestampMs: 8750,
+ },
+ ],
+ ],
+ });
+});
diff --git a/packages/captions/src/test/srt.test.ts b/packages/captions/src/test/srt.test.ts
index 24abea8cf5..883e1ed40d 100644
--- a/packages/captions/src/test/srt.test.ts
+++ b/packages/captions/src/test/srt.test.ts
@@ -1,5 +1,6 @@
import {expect, test} from 'bun:test';
import {parseSrt} from '../parse-srt';
+import {serializeSrt} from '../serialize-srt';
const input = `
1
@@ -17,8 +18,8 @@ You can use SRT files to add subtitles to your videos.
`.trim();
test('Should create captions', () => {
- const {captions: lines} = parseSrt({input});
- expect(lines).toEqual([
+ const {captions} = parseSrt({input});
+ expect(captions).toEqual([
{
confidence: 1,
endMs: 2500,
@@ -41,4 +42,7 @@ test('Should create captions', () => {
timestampMs: 8750,
},
]);
+
+ const serialized = serializeSrt({lines: captions.map((c) => [c])});
+ expect(serialized).toEqual(input);
});
diff --git a/packages/captions/src/test/tiktok.test.ts b/packages/captions/src/test/tiktok.test.ts
index 3511637a7d..b179635a11 100644
--- a/packages/captions/src/test/tiktok.test.ts
+++ b/packages/captions/src/test/tiktok.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {Caption} from '../captions';
+import {Caption} from '../caption';
import {createTikTokStyleCaptions} from '../create-tiktok-style-captions';
const captions: Caption[] = [
diff --git a/packages/docs/docs/captions/TableOfContents.tsx b/packages/docs/docs/captions/TableOfContents.tsx
index cc970f4b5e..5e58b4be84 100644
--- a/packages/docs/docs/captions/TableOfContents.tsx
+++ b/packages/docs/docs/captions/TableOfContents.tsx
@@ -12,6 +12,12 @@ export const TableOfContents: React.FC = () => {
Parse a .srt file into a <code>Caption</code> array
</div>
</TOCItem>
+ <TOCItem link="/docs/captions/serialize-srt">
+ <strong>{'serializeSrt()'}</strong>
+ <div>
+ Serialize a .srt file into a <code>Caption</code> array
+ </div>
+ </TOCItem>
<TOCItem link="/docs/captions/create-tiktok-style-captions">
<strong>{'createTikTokStyleCaptions()'}</strong>
<div>Structure the captions for TikTok-style display</div>
diff --git a/packages/docs/docs/captions/caption.mdx b/packages/docs/docs/captions/caption.mdx
index 3c2733e416..6539d5254e 100644
--- a/packages/docs/docs/captions/caption.mdx
+++ b/packages/docs/docs/captions/caption.mdx
@@ -3,7 +3,7 @@ title: Caption
crumb: '@remotion/captions'
---
-# Caption<AvailableFrom v="4.0.216 "/>
+# Caption<AvailableFrom v="4.0.216"/>
This is a simple data structure for a caption.
diff --git a/packages/docs/docs/captions/create-tiktok-style-captions.mdx b/packages/docs/docs/captions/create-tiktok-style-captions.mdx
index 138b48b9ab..f6d3a5fbca 100644
--- a/packages/docs/docs/captions/create-tiktok-style-captions.mdx
+++ b/packages/docs/docs/captions/create-tiktok-style-captions.mdx
@@ -3,7 +3,7 @@ title: createTikTokStyleCaptions()
crumb: '@remotion/captions'
---
-# createTikTokStyleCaptions()<AvailableFrom v="4.0.216 "/>
+# createTikTokStyleCaptions()<AvailableFrom v="4.0.216"/>
Using this function, you can segment tokens to create "pages" of captions, as commonly seen on TikTok videos.
diff --git a/packages/docs/docs/captions/ensure-max-characters-per-line.mdx b/packages/docs/docs/captions/ensure-max-characters-per-line.mdx
new file mode 100644
index 0000000000..1a63cdac67
--- /dev/null
+++ b/packages/docs/docs/captions/ensure-max-characters-per-line.mdx
@@ -0,0 +1,13 @@
+---
+title: ensureMaxCharactersPerLine()
+crumb: '@remotion/captions'
+---
+
+# ensureMaxCharactersPerLine()<AvailableFrom v="4.0.216"/>
+
+This is an internal, undocumented API for now.
+
+## See also
+
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/captions/src/ensure-max-characters-per-line.ts)
+- [`@remotion/captions`](/docs/captions)
diff --git a/packages/docs/docs/captions/parse-srt.mdx b/packages/docs/docs/captions/parse-srt.mdx
index e5ab2f68b4..d492ec4d42 100644
--- a/packages/docs/docs/captions/parse-srt.mdx
+++ b/packages/docs/docs/captions/parse-srt.mdx
@@ -3,7 +3,7 @@ title: parseSrt()
crumb: '@remotion/captions'
---
-# parseSrt()<AvailableFrom v="4.0.216 "/>
+# parseSrt()<AvailableFrom v="4.0.216"/>
Parses the contents of a SubRip file (`.srt`) and returns an array of [`Caption`](/docs/captions) items.
@@ -22,7 +22,6 @@ This is a demonstration of SRT subtitles.
3
00:00:07,000 --> 00:00:10,500
You can use SRT files to add subtitles to your videos.
-
`.trim();
const {captions} = parseSrt({input});
diff --git a/packages/docs/docs/captions/serialize-srt.mdx b/packages/docs/docs/captions/serialize-srt.mdx
new file mode 100644
index 0000000000..2420095a0b
--- /dev/null
+++ b/packages/docs/docs/captions/serialize-srt.mdx
@@ -0,0 +1,78 @@
+---
+title: serializeSrt()
+crumb: '@remotion/captions'
+---
+
+# serializeSrt()<AvailableFrom v="4.0.216"/>
+
+Converts a two-dimensional array of [`Caption`](/docs/captions/captions) items into a string in the SubRip format (`.srt`).
+
+```tsx twoslash title="Example usage"
+import {serializeSrt, Caption} from '@remotion/captions';
+
+const captions: Caption[] = [
+ {
+ text: 'Welcome to the Example Subtitle File!',
+ startMs: 0,
+ endMs: 2500,
+ timestampMs: 1250,
+ confidence: 1,
+ },
+ {
+ text: 'This is a demonstration of SRT subtitles.',
+ startMs: 3000,
+ endMs: 6000,
+ timestampMs: 4500,
+ confidence: 1,
+ },
+ {
+ text: 'You can use SRT files to add subtitles to your videos.',
+ startMs: 7000,
+ endMs: 10500,
+ timestampMs: 8750,
+ confidence: 1,
+ },
+];
+
+const lines = captions.map((caption) => [caption]);
+
+const serialized = serializeSrt({lines});
+
+/* serialized = `1
+00:00:00,000 --> 00:00:02,500
+Welcome to the Example Subtitle File!
+
+2
+00:00:03,000 --> 00:00:06,000
+This is a demonstration of SRT subtitles.
+
+3
+00:00:07,000 --> 00:00:10,500
+You can use SRT files to add subtitles to your videos.
+`
+*/
+```
+
+## API
+
+### `lines`
+
+An two-dimensional array of [`Caption`](/docs/captions/captions) items.
+
+Each top-level item represents a line in the SubRip file.
+
+The second-level items represent the words in that line.
+Words get concatenated together during serialization. No spaces are added between the words.
+The start timestamp is determined from the `startMs` value of the first word in the line.
+The end timestamp is determined from the `endMs` value of the last word in the line.
+
+Arrays with no items will be ignored.
+
+## Return value
+
+A string in the SubRip format (`.srt`).
+
+## See also
+
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/captions/src/serialize-srt.ts)
+- [`@remotion/captions`](/docs/captions)
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index d775b485aa..52bd9b8e6b 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -577,6 +577,7 @@ module.exports = {
items: [
'captions/caption',
'captions/parse-srt',
+ 'captions/serialize-srt',
'captions/create-tiktok-style-captions',
],
},