Skip to content

🎥 Make videos programmatically with React

feat(captions): add parseVtt()

DeryFerd0008781cff1c
diff --git a/packages/captions/src/index.ts b/packages/captions/src/index.ts
index 2440032140..6ae4c5512f 100644
--- a/packages/captions/src/index.ts
+++ b/packages/captions/src/index.ts
@@ -13,6 +13,7 @@ export {
EnsureMaxCharactersPerLineOutput,
} from './ensure-max-characters-per-line';
export {parseSrt, ParseSrtInput, ParseSrtOutput} from './parse-srt';
+export {parseVtt, ParseVttInput, ParseVttOutput} from './parse-vtt';
export {serializeSrt, SerializeSrtInput} from './serialize-srt';
export const CaptionsInternals = {
diff --git a/packages/captions/src/parse-vtt.ts b/packages/captions/src/parse-vtt.ts
new file mode 100644
index 0000000000..abbaa4021f
--- /dev/null
+++ b/packages/captions/src/parse-vtt.ts
@@ -0,0 +1,103 @@
+import type {Caption} from './caption';
+
+const parseVttTimestamp = (time: string): number => {
+ const parts = time.trim().split(':');
+ if (parts.length < 2 || parts.length > 3) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+
+ const hours = parts.length === 3 ? parts[0] : '0';
+ const minutes = parts.length === 3 ? parts[1] : parts[0];
+ const [seconds, millis] = (parts.length === 3 ? parts[2] : parts[1]).split(
+ /[,.]/,
+ );
+
+ if (!hours || !minutes || !seconds || !millis) {
+ throw new Error(`Invalid timestamp:${time}`);
+ }
+
+ return (
+ parseInt(hours, 10) * 3600000 +
+ parseInt(minutes, 10) * 60000 +
+ parseInt(seconds, 10) * 1000 +
+ parseInt(millis, 10)
+ );
+};
+
+export type ParseVttInput = {
+ input: string;
+};
+
+export type ParseVttOutput = {
+ captions: Caption[];
+};
+
+export const parseVtt = ({input}: ParseVttInput): ParseVttOutput => {
+ const inputLines = input
+ .replace(/^\uFEFF/, '')
+ .replace(/\r\n/g, '\n')
+ .replace(/\r/g, '\n')
+ .split('\n');
+ const captions: Caption[] = [];
+
+ let i = 0;
+
+ // The file starts with a `WEBVTT` header, optionally followed by trailing
+ // text on the same line.
+ if (inputLines[i]?.trim().startsWith('WEBVTT')) {
+ i++;
+ }
+
+ while (i < inputLines.length) {
+ const line = inputLines[i];
+
+ if (line.trim() === '') {
+ i++;
+ continue;
+ }
+
+ // NOTE, STYLE and REGION blocks are not cues and span until the next
+ // blank line.
+ if (/^(NOTE|STYLE|REGION)(\s|$)/.test(line)) {
+ i++;
+ while (i < inputLines.length && inputLines[i].trim() !== '') {
+ i++;
+ }
+
+ continue;
+ }
+
+ const arrowIndex = line.indexOf('-->');
+ if (arrowIndex === -1) {
+ // An optional cue identifier. Skip it and read the timing line next.
+ i++;
+ continue;
+ }
+
+ const startToken = line.slice(0, arrowIndex).trim();
+ const endToken = line
+ .slice(arrowIndex + '-->'.length)
+ .trim()
+ .split(/\s+/)[0];
+
+ const startMs = parseVttTimestamp(startToken);
+ const endMs = parseVttTimestamp(endToken);
+
+ i++;
+ const text: string[] = [];
+ while (i < inputLines.length && inputLines[i].trim() !== '') {
+ text.push(inputLines[i]);
+ i++;
+ }
+
+ captions.push({
+ text: text.join('\n').trimEnd(),
+ startMs,
+ endMs,
+ timestampMs: (startMs + endMs) / 2,
+ confidence: 1,
+ });
+ }
+
+ return {captions};
+};
diff --git a/packages/docs/docs/captions/TableOfContents.tsx b/packages/docs/docs/captions/TableOfContents.tsx
index c460394092..c5679b75d2 100644
--- a/packages/docs/docs/captions/TableOfContents.tsx
+++ b/packages/docs/docs/captions/TableOfContents.tsx
@@ -16,6 +16,12 @@ export const TableOfContents: React.FC = () => {
Parse a .srt file into a <code>Caption</code> array
</div>
</TOCItem>
+ <TOCItem link="/docs/captions/parse-vtt">
+ <strong>{'parseVtt()'}</strong>
+ <div>
+ Parse a .vtt file into a <code>Caption</code> array
+ </div>
+ </TOCItem>
<TOCItem link="/docs/captions/serialize-srt">
<strong>{'serializeSrt()'}</strong>
<div>
diff --git a/packages/docs/docs/captions/parse-vtt.mdx b/packages/docs/docs/captions/parse-vtt.mdx
new file mode 100644
index 0000000000..c08c559d3f
--- /dev/null
+++ b/packages/docs/docs/captions/parse-vtt.mdx
@@ -0,0 +1,75 @@
+---
+image: /generated/articles-docs-captions-parse-vtt.png
+title: parseVtt()
+crumb: '@remotion/captions'
+---
+
+# parseVtt()<AvailableFrom v="4.0.536"/>
+
+Parses the contents of a WebVTT file (`.vtt`) and returns an array of [`Caption`](/docs/captions/caption) items.
+
+```tsx twoslash title="Example usage"
+import {parseVtt} from '@remotion/captions';
+
+const input = `WEBVTT
+
+00:00:00.000 --> 00:00:02.500
+Welcome to the Example WebVTT File!
+
+00:00:03.000 --> 00:00:06.000
+This is a demonstration of WebVTT subtitles.
+`.trim();
+
+const {captions} = parseVtt({input});
+
+/* captions = [
+ {
+ confidence: 1,
+ endMs: 2500,
+ startMs: 0,
+ text: 'Welcome to the Example WebVTT File!',
+ timestampMs: 1250,
+ },
+ {
+ confidence: 1,
+ endMs: 6000,
+ startMs: 3000,
+ text: 'This is a demonstration of WebVTT subtitles.',
+ timestampMs: 4500,
+ },
+]
+*/
+```
+
+## API
+
+### `input`
+
+The contents of a `.vtt` file as a `string`.
+
+## Return value
+
+An object with the following properties:
+
+### `captions`
+
+An array of [`Caption`](/docs/captions/caption) items.
+
+## Behavior
+
+- The `WEBVTT` header is optional and ignored, including any trailing text on the header line.
+- A cue may be preceded by an optional identifier on its own line.
+- Timestamps accept both `HH:MM:SS.mmm` and the shorter `MM:SS.mmm` form, and a comma may be used as the millisecond separator.
+- Cue settings after the timestamps (such as `align:start position:10%`) are ignored.
+- `NOTE`, `STYLE` and `REGION` blocks are skipped.
+- Multi-line cue text is joined with `\n`.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />
+
+## See also
+
+- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/captions/src/parse-vtt.ts)
+- [`parseSrt()`](/docs/captions/parse-srt)
+- [`@remotion/captions`](/docs/captions/api)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index d49c152831..d8a0c3f601 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -242,6 +242,7 @@ const sidebars: SidebarsConfig = {
items: [
'captions/caption',
'captions/parse-srt',
+ 'captions/parse-vtt',
'captions/serialize-srt',
'captions/create-tiktok-style-captions',
],