@lp-labs/srt-codec
v0.1.0
Published
Robust SubRip (SRT) subtitle parser and formatter with millisecond timestamps.
Readme
@lp-labs/srt-codec
Robust SubRip (SRT) subtitle parser and formatter: exact millisecond timestamps, cue numbers, multi-line text, blank-line separation, CRLF/CR/BOM handling and line-numbered errors. Text markup is preserved verbatim, never sanitized or rendered.
Install
npm install @lp-labs/srt-codecNode.js 18+; standalone ES2022 core with DOM-library types only. Zero runtime or peer dependencies. ESM and CommonJS builds with separate declarations. No filesystem, network, timer or environment access: every function works on in-memory bytes or strings you provide.
Quickstart
import { formatSrt, parseSrt } from '@lp-labs/srt-codec';
const cues = parseSrt('1\n00:00:01,000 --> 00:00:02,500\nHello <i>world</i>\n\n');
console.log(cues);
console.log(JSON.stringify(formatSrt([{ index: 1, startMs: 0, endMs: 1500, text: 'Hi' }])));CommonJS consumers use const api = require('@lp-labs/srt-codec'). The same named API is available in both module formats. No default export.
API, behavior and options
parseSrt(text, options?) returns SrtCue[] with index, startMs, endMs, text and optional settings (anything after the end timestamp, usually X1:.. X2:.. coordinates). A leading BOM is removed and CRLF, CR and LF line endings are all accepted. Cues are separated by blank (or whitespace-only) lines. The cue number line is optional; when absent the running number is used. Text lines are joined with \n and kept exactly, including markup such as <i> or {\an8}. A cue may have no text.
Timestamps are H{1,3}:MM:SS,mmm or with a . separator; minutes and seconds must be below 60 and milliseconds must be exactly three digits. The end may equal but not precede the start. By default, a digits-only line directly followed by a timing line starts a new cue even if the blank separator is missing (a common real-world defect); pass strictBlocks: true to reject that instead.
formatSrt(cues, options?) emits number line, timing line, text lines and a blank line per cue, ending with a blank line. renumber (default true) writes 1..n; false writes each cue's index. lineEnding is '\n' (default) or '\r\n'. Text that contains a blank line or the sequence --> is rejected because it would not read back as the same cue. parseSrtTimestamp(text) returns milliseconds or undefined; formatSrtTimestamp(ms) writes HH:MM:SS,mmm for 0..MAX_SRT_MS (99:59:59,999). Parse options: maxCues (100,000) and maxLength (16,777,216 characters).
All exports: SrtCue, SrtParseOptions, SrtFormatOptions, SrtError, MAX_SRT_MS, parseSrtTimestamp, formatSrtTimestamp, parseSrt, formatSrt.
Full TypeScript declarations
export interface SrtCue {
/** Cue number as written in the file (or the running number when the file omits it). */
readonly index: number;
/** Start time in milliseconds. */
readonly startMs: number;
/** End time in milliseconds (never before startMs). */
readonly endMs: number;
/** Text lines joined with "\n". Markup such as <i> or {\an8} is preserved verbatim. */
readonly text: string;
/** Anything after the end timestamp on the timing line (often X1:.. Y1:.. coordinates), trimmed. */
readonly settings?: string;
}
export interface SrtParseOptions {
/** Maximum cues. Default 100,000. */
maxCues?: number;
/** Maximum input length in UTF-16 units. Default 16,777,216. */
maxLength?: number;
/**
* Default false: a number line directly followed by a timing line starts a new cue even without
* a blank separator line. Set true to require blank lines between cues.
*/
strictBlocks?: boolean;
}
export interface SrtFormatOptions {
/** Line terminator. Default "\n". */
lineEnding?: '\n' | '\r\n';
/** Number cues 1..n (default true). When false each cue's own index is written. */
renumber?: boolean;
}
export declare class SrtError extends Error {
/** 1-based line number, or 0 when not line-specific. */
readonly line: number;
constructor(message: string, line: number);
}
export declare const MAX_SRT_MS = 359999999;
/** Parses HH:MM:SS,mmm (a "." separator is also accepted) into milliseconds; returns undefined if invalid. */
export declare function parseSrtTimestamp(value: string): number | undefined;
/** Formats milliseconds as HH:MM:SS,mmm (hours at least two digits, at most 99). */
export declare function formatSrtTimestamp(ms: number): string;
/** Parses SubRip text (CRLF, LF or CR line endings, optional BOM). */
export declare function parseSrt(input: string, options?: SrtParseOptions): SrtCue[];
/** Formats cues as SubRip text ending with a blank line after the last cue. */
export declare function formatSrt(cues: readonly SrtCue[], options?: SrtFormatOptions): string;Examples
Shifting subtitles by two seconds
import { formatSrt, parseSrt } from '@lp-labs/srt-codec';
const source =
'1\r\n00:00:01,000 --> 00:00:02,000\r\nFirst\r\n\r\n2\r\n00:00:03,000 --> 00:00:04,000\r\nSecond\r\n';
const shifted = parseSrt(source).map((cue) => ({
...cue,
startMs: cue.startMs + 2000,
endMs: cue.endMs + 2000,
}));
console.log(formatSrt(shifted));Error reporting
import { SrtError, parseSrt } from '@lp-labs/srt-codec';
try {
parseSrt('1\n00:00:05,000 --> 00:00:01,000\nBackwards\n');
} catch (error) {
console.log(error instanceof SrtError, error.line, error.message);
}Customization
Tighten maxCues/maxLength for untrusted files, choose strictBlocks for validators, and pick lineEnding for your target player. Interpret markup yourself after parsing; if you render text into HTML you must escape or sanitize it, because this library does neither.
Errors
Malformed files throw SrtError with a 1-based line (0 for whole-input limits). Bad arguments throw TypeError/RangeError. Parsing never returns partial results.
Performance
Linear in input size: one split into lines and one pass. Memory is proportional to the number of lines plus parsed cues. All limits are enforced before large allocations where the input length is known.
Scope and non-goals
Implements the widely used SubRip conventions only (there is no formal standard). Not provided: HTML/ASS tag parsing, sanitization, frame-rate conversion, encoding detection (decode bytes to a string first), overlap/ordering validation, or file I/O. Millisecond precision only; cues longer than 99 hours cannot be formatted.
Development
npm ci --offline
npm run typecheck
npm test
npm run format:checkTypeScript ^5.9.3 and Prettier ^3.6.2 are development-only. Build emits dist/esm and dist/cjs. Tests use Node's test runner; consumer.mts and consumer.cts exercise bare package imports including negative type assertions.
Support
If this library is useful to you, consider supporting its maintenance with a donation via PayPal.
Author
Created by Libin Prasanth. Connect on LinkedIn for updates and discussion.
