Media Captions
Captions parsing and rendering library built for the modern web.
Features
- 🚯 0 dependencies.
- 💪 Built with TypeScript (TS 5 bundle mode ready).
- 🪶 5kB total + modular (parser/renderer split) + tree-shaking support.
- 💤 Parsers are lazy loaded on-demand.
- 🚄 Efficiently load and apply styles in parallel via CSS files.
- 🗂️ Supports VTT, SRT, and SSA/ASS.
- ⬆️ Roll-up captions via VTT regions.
- 🧰 Modern
fetch and ReadableStream APIs.
- 📡 Chunked text and response streaming support.
- 📝 WebVTT spec-compliant settings and rendering.
- 🎤 Timed text-tracks for karaoke-style captions.
- 🛠️ Supports custom captions parser and cue renderer.
- 💥 Collision detection to avoid overlapping or out-of-bounds cues.
- 🏗️ Fixed and in-order cue rendering (including on font or overlay size changes).
- 🛑 Adjustable parsing error-tolerance with strict and non-strict modes.
- 🖥️ Works in the browser and server-side (string renderer).
- 🎨 Easy customization via CSS.
➕ Planning to also add a TTML, CEA-608, and CEA-708 parser that will map to VTT and render
correctly. In addition, custom font loading and text codes support is planned for SSA/ASS captions.
We don't have an exact date but most likely after the Vidstack Player 1.0. If
urgent and you're willing to sponsor, feel free to email me at rahim.alwer@gmail.com.
🔗 Quicklinks
Demo
The StackBlitz link below showcases a simple example of how captions are fetched, parsed, and
rendered over a native video element. We plan on adding more examples for additional captions
formats and scenarios.

Motivation
❓ Are native captions not good enough?
Simply put, no.
- Positioning, styling, and rendering of cues is interpreted differently across browsers (i.e.,
not consistent).
- Styling customization via pseudo
::cue selector is inconsistent across browsers and severely
limited with respect to even basic movement and styles.
- Cues can not be easily or accurately moved which means they'll become hidden when custom controls
are active.
- Multiple active cues are not rendered in the correct order. This can also occur randomly on font
and overlay size changes (e.g., entering fullscreen).
- Failure in positioning and customizing styles correctly results in failing accessibility
guidelines.
- Text tracks cannot be removed in most browsers as there's no native API to do so. Captions need
to be managed externally and mapped to a generic text track.
- Karaoke-style captions are not supported out of the box in most browsers.
- Only VTT is natively supported by browsers.
- VTT Regions and roll-up captions are not fully supported in all browsers.
- Custom rendering of cues is not supported.
- Large caption files can not be streamed and aborted when no longer required.
- Obviously can not be used server-side.
Did you know closed-captions are governed by the Federal Communications Commission (FCC) under the
Communications and Video Accessibility Act (CVA)? Not providing captions and adequate
customization options on the web for content that was shown on TV doesn't meet guidelines 😱 Filed
law suits have dramatically increased in recent years! See the amazing
Caption Me If You Can talk at Demuxed by Dan Sparacio to learn more.
❓ What about mozilla/vtt?
The library is old, outdated, and unmaintained.
- Not packaged correctly by modern standards using Node exports with ES6, TS types, CJS/ESM,
and server bundles.
- Doesn't lazy load the parser.
- Doesn't cleanly work server-side out of the box.
- Doesn't split parser and renderer so they can be imported separately when needed.
- Not built with TypeScript so no types are shipped.
- Doesn't support a wide variety features that we support. Including streaming via modern APIs,
VTT regions, roll-up captions, custom renderers, alternative captions formats (SRT/SSA),
timed-text and more.
- In-lines all styles which means they can't be loaded in parallel with JS, makes it harder to
customize, and slower with respect to DOM updates.
- Doesn't include flexible error tolerance settings.
- Doesn't expose styling attrs for selecting nodes such as cues, voice nodes, and timed-text nodes.
Installation
First, install the NPM package:
npm i media-captions
Next, include styles if you plan on rendering captions using the CaptionsRenderer:
import 'media-captions/styles/captions.css';
// Optional - include if rendering VTT regions.
import 'media-captions/styles/regions.css';
Optionally, you can load the styles directly from a CDN using JSDelivr
like so:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/media-captions/styles/captions.min.css" />
<!-- Optional - include if rendering VTT regions. -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/media-captions/styles/regions.min.css" />
API
Parse Options
All parsing functions exported from this package accept the following options:
strict: Whether strict mode is enabled. In strict mode parsing errors will throw and cancel
the parsing process.
errors: Whether errors should be collected and reported in the final
parser result. By default, this value will be true in dev mode or if strict
mode is true. If set to true and strict mode is false, the onError callback will be invoked.
Do note, setting this to true will dynamically load error builders which will slightly increase
bundle size (~1kB).
type: The type of the captions file format so the correct parser is loaded. Options
include vtt, srt, ssa, ass, or a custom CaptionsParser object.
onHeaderMetadata: Callback that is invoked when the metadata from the header block has been
parsed.
onCue: Invoked when parsing a VTT cue block has finished parsing and a VTTCue has
been created. Do note, regardless of which captions file format is provided a VTTCue will
be created.
onRegion: Invoked when parsing a VTT region block has finished and a VTTRegion has been
created.
onError: Invoked when a loading or parser error is encountered. Do note, this is only invoked
in development, if the strict parsing option is true, or if the errors parsing option is
true.
Options can be provided to any parsing function like so:
import { parseText } from 'media-captions';
parseText('...', {
strict: false,
type: 'vtt',
onCue(cue) {
// ...
},
onError(error) {
// ...
},
});
Parse Result
All parsing functions exported from this package return a Promise which will resolve a
ParsedCaptionsResult object with the following properties:
metadata: An object containing all metadata that was parsed from the header block.
regions: An array containing VTTRegion objects that were parsed and created during the
parsing process.
cues: An array containing VTTCue objects that were parsed and created during the parsing
process.
errors: An array containing ParseError objects. Do note, errors will only be collected if
in development mode, if strict parsing option is set to true, or the errors parsing option is
set to true.
import { parseText } from 'media-captions';
// `ParsedCaptionsResult`
const { metadata, regions, cues, errors } = await parseText('...');
for (const cue of cues) {
// ...
}
Parse Errors
By default, parsing is error tolerant and will always try to recover. You can set strict mode
to ensure errors are not tolerated and are instead thrown. The text stream and parsing process
will also be cancelled.
import { parseText, type ParseError } from 'media-captions';
try {
// Any error will now throw and cancel parsing.
await parseText('...', { strict: true });
} catch (error: ParseError) {
console.log(error.code, error.message, error.line);
}
A more tolerant error collection option is to set the errors parsing option to true. This
will ensure the onError callback is invoked and also errors are reported in the final
result (this will add ~1kB to the bundle size):
import { parseText } from 'media-captions';
const { errors } = await parseText('...', {
errors: true, // Not required if you only want errors in dev mode.
onError(error) {
error; // `ParseError`
},
});
for (const error of errors) {
// ...
}
The ParseError contains a numeric error code that matches the following values:
const ParseErrorCode = {
LoadFail: 0,
BadSignature: 1,
BadTimestamp: 2,
BadSettingValue: 3,
BadFormat: 4,
UnknownSetting: 5,
};
The ParseErrorCode object can be imported from the package.
parseText
This function accepts a text string as input to be parsed:
import { parseText } from 'media-captions';
const { cues } = await parseText('...');
parseTextStream
This function accepts a text stream ReadableStream<string> as input to be parsed:
import { parseTextStream } from 'media-captions';
const stream = new ReadableStream<string>({
start(controller) {
controller.enqueue('...');
controller.enqueue('...');
controller.enqueue('...');
// ...
controller.close();
},
});
// `ParsedCaptionsResult`
const result = await parseTextStream(stream, {
onCue(cue) {
// ...
},
});
parseResponse
The parseResponse function accepts a Response or Promise<Response> object. It can be seamlessly used with
fetch to parse a response body stream like so:
import { ParseErrorCode, parseResponse } from 'media-captions';
// `ParsedCaptionsResult`
const result = await parseResponse(fetch('/media/subs/english.vtt'), {
onCue(cue) {
// ...
},
onError(error) {
if (error.code === ParseErrorCode.LoadFail) {
console.log(error.message);
}
},
});
The captions type will inferred from the response header content-type field. You can specify
the specific captions format like so:
parseResponse(..., { type: 'vtt' });
The text encoding will be inferred from the response header and forwarded to the underlying
TextDecoder. You
can specify a specific encoding like so:
parseResponse(..., { encoding: 'utf8' });
parseByteStream
This function is used to parse byte streams ReadableStream<Uint8Array>. It's used by the
parseResponse function to parse response body streams. It can be used like so:
import { parseByteStream } from 'media-captions';
const byteStream = new ReadableStream<Uint8Array>({
// ...
});
const result = await parseByteStream(byteStream, {
encoding: 'utf8',
onCue(cue) {
// ...
},
});
CaptionsParser
You can create a custom caption parser and provide it to the type option on any parse function.
The parser can be created and provided like so: