DEV Community

eth shihao
eth shihao

Posted on

Netflix timed text QC in TypeScript with CPS, CPL, and cue gaps

A 42-character cue displayed for two seconds fits on one line and reads at 21 characters per second. It passes the line-length check and exceeds the Netflix English (USA) adult reading-speed limit. At 24 fps, a 125 ms gap between frame-aligned cues adds a separate finding. Three frames is enough to clear the minimum, but still falls in the range that calls for a timing review. Netflix English (USA) Timed Text Style Guide · Netflix Subtitle Timing Guidelines

Turn the delivery profile into checks

Check English (USA) screening rule
CPS, characters per second At most 20 for adult programs or 17 for children's programs
CPL, characters per line At most 42 per line and two lines per cue
Gap At least two frames. Review gaps longer than two frames and shorter than half a second.

Netflix counts spaces and punctuation. This example strips common SRT styling, decodes a small set of named entities, and counts Unicode grapheme clusters per line. The visual line break itself adds no character. Use the requested language and deliverable profile when choosing thresholds. English subtitle templates, for example, have their own reading-speed limits. Netflix reading-speed counting · Netflix subtitle template rules

Parse the file, then evaluate the cues

An SRT block has a numeric cue ID, a timing line, and one or more text lines. The parser handles a UTF-8 BOM and common newline conventions. Malformed blocks raise an error with their block number. Timing findings such as reversed ranges are reported during QC so other valid cues can still be checked. Library of Congress SubRip format description

Save the following as subtitle-qc.mts. Run node subtitle-qc.mts with Node.js 24 to execute the fixture, or node subtitle-qc.mts episode.en-US.srt to check a UTF-8 file.

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";

type Cue = { id: string; startMs: number; endMs: number; lines: string[] };
const range = /^(\d{2}:[0-5]\d:[0-5]\d,\d{3})[ \t]+-->[ \t]+(\d{2}:[0-5]\d:[0-5]\d,\d{3})$/;
const milliseconds = (stamp: string) => {
  const [hours, minutes, seconds, millis] = stamp.split(/[:,]/).map(Number);
  return ((hours * 60 + minutes) * 60 + seconds) * 1000 + millis;
};

function parseSrt(input: string): Cue[] {
  const normalized = input.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n")
    .replace(/^(?:[ \t]*\n)+|(?:\n[ \t]*)+$/g, "");
  if (!normalized.trim()) throw new Error("Empty SRT");
  return normalized.split(/\n(?:[ \t]*\n)+/).map((block, i) => {
    const [id, timing = "", ...lines] = block.split("\n");
    const match = range.exec(timing.trim());
    if (!/^\d+$/.test(id.trim()) || !match || lines.length === 0) {
      throw new Error("Malformed SRT block " + (i + 1));
    }
    return { id: id.trim(), startMs: milliseconds(match[1]), endMs: milliseconds(match[2]), lines };
  });
}

const entities: Record<string, string> = {
  amp: "&", lt: "<", gt: ">", quot: '"', nbsp: "\u00a0",
};
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
function visibleCharacters(line: string): number {
  const text = line
    .replace(/<\/?(?:[bius]|font)(?:\s+[^<>]*)?>/gi, "")
    .replace(/&(amp|lt|gt|quot|nbsp);/g, (_, name: string) => entities[name]);
  return Array.from(segmenter.segment(text)).length;
}

type Profile = { maxCps: number; maxCpl: number; maxLines: number; fps: [number, number] };
const englishAdult24: Profile = { maxCps: 20, maxCpl: 42, maxLines: 2, fps: [24, 1] };
type Finding = { cue: string; rule: string; measured: number; after?: string; line?: number };

function check(cues: Cue[], profile: Profile): Finding[] {
  const [numerator, denominator] = profile.fps;
  const frame = (ms: number) => Math.round(ms * numerator / (1000 * denominator));
  const findings: Finding[] = [];
  let latestEnding: Cue | undefined;

  for (const cue of [...cues].sort((a, b) => a.startMs - b.startMs)) {
    const duration = cue.endMs - cue.startMs;
    if (duration <= 0) {
      findings.push({ cue: cue.id, rule: "invalid-duration-ms", measured: duration });
      continue;
    }

    if (cue.lines.length > profile.maxLines) {
      findings.push({ cue: cue.id, rule: "line-count", measured: cue.lines.length });
    }
    const lengths = cue.lines.map(visibleCharacters);
    lengths.forEach((length, index) => {
      if (length > profile.maxCpl) {
        findings.push({ cue: cue.id, rule: "cpl", measured: length, line: index + 1 });
      }
    });
    const count = lengths.reduce((total, length) => total + length, 0);
    if (count * 1000 > profile.maxCps * duration) {
      findings.push({ cue: cue.id, rule: "cps", measured: count * 1000 / duration });
    }

    if (latestEnding) {
      const gapMs = cue.startMs - latestEnding.endMs;
      const gapFrames = frame(cue.startMs) - frame(latestEnding.endMs);
      const link = { cue: cue.id, after: latestEnding.id };
      if (gapMs < 0) {
        findings.push({ ...link, rule: "overlap-ms", measured: -gapMs });
      } else if (gapFrames < 2) {
        findings.push({ ...link, rule: "short-gap-frames", measured: gapFrames });
      } else if (gapFrames > 2 && 2 * gapFrames * denominator < numerator) {
        findings.push({ ...link, rule: "review-chaining-frames", measured: gapFrames });
      }
    }
    if (!latestEnding || cue.endMs > latestEnding.endMs) latestEnding = cue;
  }
  return findings;
}

const fixture = [
  "1\r\n00:00:00,000 --> 00:00:01,000\r\n<i>We are ready.</i>",
  "2\r\n00:00:01,125 --> 00:00:02,125\r\nThis line is deliberately longer than forty-two characters.",
  "3\r\n00:00:02,167 --> 00:00:04,000\r\nWait &amp; watch.",
  "4\r\n00:00:03,500 --> 00:00:04,500\r\nAlready?",
].join("\r\n\r\n");

const file = process.argv[2];
const findings = check(parseSrt(file ? readFileSync(file, "utf8") : "\uFEFF" + fixture), englishAdult24);
if (!file) {
  assert.equal(visibleCharacters("<i>Cafe\u0301 &amp; tea.</i>"), 11);
  assert.deepEqual(findings, [
    { cue: "2", rule: "cpl", measured: 59, line: 1 },
    { cue: "2", rule: "cps", measured: 59 },
    { cue: "2", after: "1", rule: "review-chaining-frames", measured: 3 },
    { cue: "3", after: "2", rule: "short-gap-frames", measured: 1 },
    { cue: "4", after: "3", rule: "overlap-ms", measured: 500 },
  ]);
}
console.table(findings);
Enter fullscreen mode Exit fullscreen mode

Review gaps against the cut

SRT stores milliseconds. The example rounds each endpoint to the nearest frame for gap checks and uses the original millisecond endpoints for duration and overlap. Use the source frame rate, such as [24000, 1001] for 23.976 fps. If the delivery workflow supplies exact frame indexes, use them directly. The running latest end also catches nested overlaps where pairing only adjacent rows would miss a cue that is still on screen.

Review flagged gaps alongside the audio waveform and shot changes. Extending a cue to close a gap can carry the line across a cut or into a different speaker's delivery. For handoff, keep cue IDs and original files alongside the report so a reviewer can reproduce each finding. Netflix timing guidance

SubPackQC is published by the team behind this article. Its browser workflow checks SRT and WebVTT sidecars, matches tracks against a manifest, and prepares a QA sign-off for the delivery batch. SubPackQC

AI disclosure. This article was generated with AI.

Top comments (0)