DEV Community

eth shihao
eth shihao

Posted on

Benchmarking SRT and WebVTT subtitle QC in JavaScript

A half-second cue containing <i>OK</i><b>!</b> renders as OK! at 6 characters per second. Counting the raw 17 JavaScript code units makes it appear to run at 34 CPS. That shortcut also misses a second failure when the cue sits inside a long-running subtitle and a later cue starts before the long cue ends.

Count what reaches the screen

Strip supported formatting tags and decode entities before counting. Then segment the result by grapheme. An accented letter formed from two code points counts as one grapheme, and an emoji joined with a zero-width joiner can also count as one. The linter counts spaces within lines, counts line length per visible line, and divides total visible characters by cue duration in seconds.

For timing, keep the cue with the latest ending time as you scan starts in order. In the fixture below, the first cue is still live at 1,500 ms even though the second cue ended at 1,000 ms. The cut list is separate. A cue that starts at 2,580 ms is 20 ms before the 2,600 ms cut and fails an 80 ms threshold. A boundary exactly aligned with a cut passes under this profile.

Cue Start to end (ms) Expected result
1 0 to 2,500 Clear
2 500 to 1,000 Overlap with cue 1
3 1,500 to 2,000 22 CPS, 11 characters on one line, overlap with cue 1
4 2,580 to 3,500 20 ms start-to-cut clearance

Run the benchmark

The script builds each track from 1,000 copies of the four-cue fixture, with a 5-second stride. Assertions verify cue-level findings in both formats. The raw-length and adjacent-overlap checks illustrate the shortcuts, then the timer measures only the full QC pipeline. Run from the repository root on Node.js 20 or later. MIT source and tests

node --input-type=module <<'JS'
import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
import { lintSubtitles, parseSubtitles } from './src/index.js';

const groups = 1000;
const shots = Array.from({ length: groups }, (_, i) => 5000 * i + 2600);
const pattern = [
  [0, 2500, 'Start'],
  [500, 1000, '<i>OK</i><b>!</b>'],
  [1500, 2000, '01234567890'],
  [2580, 3500, 'Done'],
];
const stamp = (ms, vtt) =>
  new Date(ms).toISOString().slice(11, 23).replace('.', vtt ? '.' : ',');
const options = { maxCps: 20, maxLineLength: 10, minShotGapMs: 80, shotCutsMs: shots };
const expected = [
  ['OVERLAP', 2], ['LINE_LENGTH', 3], ['CPS', 3], ['OVERLAP', 3], ['SHOT_GAP', 4],
];

for (const vtt of [false, true]) {
  const blocks = [];
  for (let i = 0; i < groups; i++) {
    for (const [start, end, payload] of pattern) {
      const base = 5000 * i;
      blocks.push([blocks.length + 1, stamp(base + start, vtt) + ' --> ' + stamp(base + end, vtt), payload].join('\n'));
    }
  }
  const text = (vtt ? 'WEBVTT\n\n' : '') + blocks.join('\n\n');
  const parsed = parseSubtitles(text);
  let rawCpsFlags = 0;
  let adjacentOverlaps = 0;
  parsed.cues.forEach((cue, index) => {
    if (cue.textLines.join('').length * 1000 > 20 * (cue.endMs - cue.startMs)) rawCpsFlags++;
    if (index > 0 && cue.startMs < parsed.cues[index - 1].endMs) adjacentOverlaps++;
  });
  assert.equal(rawCpsFlags, 2 * groups);
  assert.equal(adjacentOverlaps, groups);

  const report = lintSubtitles(text, options);
  assert.deepEqual(report.summary, { cues: 4 * groups, errors: 2 * groups, warnings: 3 * groups });
  for (let i = 0; i < groups; i++) {
    const found = report.issues.slice(5 * i, 5 * (i + 1))
      .map(({ code, cueIndex }) => [code, cueIndex - 4 * i]);
    assert.deepEqual(found, expected);
  }

  for (let i = 0; i < 5; i++) lintSubtitles(text, options);
  const samples = [];
  for (let i = 0; i < 21; i++) {
    const started = performance.now();
    const result = lintSubtitles(text, options);
    samples.push(performance.now() - started);
    assert.equal(result.issues.length, 5 * groups);
  }
  samples.sort((a, b) => a - b);
  const median = samples[Math.floor(samples.length / 2)];
  console.log(JSON.stringify({
    node: process.version, platform: process.platform, arch: process.arch,
    format: report.format, cues: report.summary.cues, issues: report.issues.length,
    rawCpsFlags, adjacentOverlaps, medianMs: Number(median.toFixed(2)),
    cuesPerSecond: Math.round(report.summary.cues * 1000 / median),
  }));
}
JS
Enter fullscreen mode Exit fullscreen mode

Each 4,000-cue track produces 1,000 CPS warnings, 1,000 line-length warnings, 2,000 overlaps, and 1,000 shot-gap warnings. The raw counter adds 1,000 false CPS flags for the styled cue. Comparing only adjacent cues misses 1,000 overlaps. Runtime includes parsing, grapheme counts, issue allocation, sorting, and cut lookup. This synthetic track measures these rules on predictable data. Tune the thresholds and character-count policy to the delivery brief before applying them to an episode.

One local run on arm64 macOS with Node.js 24.15.0 measured median times of 9.91 ms for SRT and 6.64 ms for WebVTT. Each median comes from 21 timed passes over the same 4,000-cue track after five warmups.

Load either sample in the browser demo, then change or remove the cut times to see which diagnostics depend on them. Subtitles stay in the browser tab. Interactive QC demo

SubPackQC, from the team behind this article, covers subtitle delivery workflows with multiple tracks. SubPackQC

Top comments (0)