03:00:0050% OFFClaim

Validate SRT cue overlap, duration and media boundaries

Run a strict text-only SRT timing validator against three accepted cues and six original invalid files, without font discovery or subtitle burn-in.

Reject ambiguous cue order, zero-length captions, overlap and past-end timing before rendering. This recipe only covers the declared simple SRT subset and an explicitly generated two-second media boundary.

Previously recorded numerical observations below describe the original local fixture runs. For a reproduction, use the new receipt and its actual tool versions and hashes; an old observation is not a guaranteed result on every installation.

Preparation

  • Save each complete code block below under its displayed filename in one empty local folder. Run commands from that folder. The scripts create their synthetic inputs and manifests in the chosen output directory; inspect those files after running. Use an output directory that does not already exist. All relative paths below refer to this working folder.
  • Use Node.js without any third-party package or FFmpeg. The duration.json fixture explicitly supplies a 2,000-millisecond media boundary.
  • Read valid.srt: cue 1 spans 0–700 ms, cue 2 spans 700–1,400 ms and cue 3 spans 1,500–2,000 ms. Adjacent cues and a final end equal to media duration are allowed.
  • Keep the strict format HH:MM:SS,mmm --> HH:MM:SS,mmm, sequential cue indices and nonempty text. The fixture is plain text and makes no font or burn-in claim.

Run

node run-recipe.mjs --out ./my-run

01. Define the timing policy before parsing

The fixture uses integer milliseconds, sequential indices starting at one, no overlap and end > start. The media boundary is an explicit input; the script does not discover a video’s real duration. The one-hundred-millisecond gap before cue 3 is intentional.

02. Parse the accepted cues

Run the command and inspect cue-table.json. It contains the three actual parsed start/end values. A cue starting exactly at the previous cue’s end is accepted, and the last cue may end exactly at 2,000 ms.

03. Replay six invalid subtitle files

The runner writes and tests overlapping, zero-duration, past-boundary, wrong-index, malformed-millisecond and invalid-minute variants. Each expected rejection records its concrete validation error. A correctly shaped timestamp with a minute component of 60 is still invalid.

04. Hand off validated timing for a separate render

Check all nine assertions and retain the cue table beside the original SRT. Font coverage, line layout, reading speed, HTML extensions and rendered appearance remain separate tasks. This timing validator does not check a CJK font inventory or render subtitles.

Acceptance

  • The generated valid.srt parses into exactly three cue rows with integer milliseconds.
  • Cue 2 starting at cue 1’s 700-ms end is accepted.
  • The final cue ending exactly at the 2,000-ms media boundary is accepted.
  • Overlap and zero-length cue variants are rejected with different recorded reasons.
  • A cue ending at 2,001 ms and nonsequential numbering are rejected.
  • Malformed milliseconds and a minute component of 60 are rejected; all nine checks pass.

Troubleshooting

Adjacent captions are incorrectly flagged as overlap.

Use start >= previousEnd for the no-overlap rule and rerun the 700-ms boundary case.

The last cue is rejected at the video end.

Verify the explicitly generated durationMilliseconds first. If it is correct, allow end equal to that boundary while still rejecting 2,001 ms.

A well-formatted cue has no visible time.

Change only end so it is strictly later than start, then recheck overlap against the next cue. Do not delete the zero-duration rule.

Keep with the result

Validated timings are a handoff input for a render stage. They do not prove a particular font displays, captions fit the frame or viewers can comfortably read the text.

Complete source and input construction

Save every file below with its exact filename in the same folder. The source includes the input definitions and construction logic; code blocks are complete, including all companion modules.

common.mjs

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { deflateSync } from 'node:zlib';
import { spawnSync } from 'node:child_process';
import http from 'node:http';
export { fs, path, http };
export const sha = b => createHash('sha256').update(b).digest('hex');
export const ensure = (v,m) => { if (!v) throw new Error(m); };
export const json = (p,v) => fs.writeFileSync(p,JSON.stringify(v,null,2)+'\n');
export function png(w,h,colour) {
  const raw=Buffer.alloc(h*(w*3+1));
  for(let y=0;y<h;y++) for(let x=0;x<w;x++) { const c=typeof colour==='function'?colour(x,y):colour; for(let k=0;k<3;k++) raw[y*(w*3+1)+1+x*3+k]=c[k]; }
  const crc=b=>{let c=0xffffffff;for(const n of b){c^=n;for(let j=0;j<8;j++)c=(c>>>1)^((c&1)?0xedb88320:0);}return(c^0xffffffff)>>>0;};
  const chunk=(t,b)=>{const n=Buffer.alloc(4),s=Buffer.from(t),c=Buffer.alloc(4);n.writeUInt32BE(b.length);c.writeUInt32BE(crc(Buffer.concat([s,b])));return Buffer.concat([n,s,b,c]);};
  const head=Buffer.alloc(13);head.writeUInt32BE(w);head.writeUInt32BE(h,4);head[8]=8;head[9]=2;
  return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',head),chunk('IDAT',deflateSync(raw)),chunk('IEND',Buffer.alloc(0))]);
}
export function dimensions(b){ensure(b.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),'PNG_SIGNATURE');return[b.readUInt32BE(16),b.readUInt32BE(20)];}
export const maxDelta=(a,b)=>{ensure(a.length===b.length,'BYTE_LENGTH');let d=0;for(let i=0;i<a.length;i++)d=Math.max(d,Math.abs(a[i]-b[i]));return d;};
export const safeName=s=>typeof s==='string'&&/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(s);
export async function request(url,method='GET',body){
  const u=new URL(url);ensure(u.hostname==='127.0.0.1'&&u.protocol==='http:','LOOPBACK_ONLY');
  return await new Promise((resolve,reject)=>{const q=http.request(u,{method,agent:false,headers:body?{'content-type':'application/json'}:{}},r=>{let size=0;const a=[];r.on('data',b=>{size+=b.length;if(size>2*1024*1024){r.destroy(new Error('RESPONSE_LIMIT'));return;}a.push(b);});r.on('error',reject);r.on('end',()=>resolve({status:r.statusCode,body:Buffer.concat(a)}));});q.setTimeout(3000,()=>q.destroy(new Error('HTTP_TIMEOUT')));q.on('error',reject);q.end(body===undefined?undefined:JSON.stringify(body));});
}
export async function closeServer(server){await new Promise((resolve,reject)=>{server.close(e=>e?reject(e):resolve());server.closeAllConnections();});}
export async function run(task,fn,media=false){
 const here=path.dirname(fileURLToPath(import.meta.url));const args=process.argv.slice(2);ensure(args.length===0||(args.length===2&&args[0]==='--out'),'USAGE: node run-recipe.mjs --out NEW_DIRECTORY');
 const out=path.resolve(args[1]||path.join(here,'my-run'));ensure(!fs.existsSync(out),'REFUSE_OVERWRITE');fs.mkdirSync(out,{recursive:true});
 const tmp=path.join(out,'.tmp');fs.mkdirSync(tmp);const tests=[],failures=[],commands=[];const scripts=Object.fromEntries(['run-recipe.mjs','common.mjs'].map(n=>[n,sha(fs.readFileSync(path.join(here,n)))]));
 const h={out,tmp,info:{},p:n=>path.join(out,n),check:(name,v,detail={})=>{ensure(v,`CHECK_FAILED:${name}`);tests.push({name,passed:true,...detail});},reject:(name,fn,pattern)=>{let e;try{fn();}catch(x){e=x;}ensure(e&&(!pattern||pattern.test(e.message)),`EXPECTED_REJECTION_MISSING:${name}`);const r={name,passed:true,expectedRejection:true,error:String(e.message).slice(0,900)};tests.push(r);failures.push(r);}};
 const bin=process.env.FFMPEG_BIN||'ffmpeg';
 h.ff=(args,allowFailure=false)=>{const all=['-hide_banner','-nostdin','-loglevel','error','-threads','1','-filter_threads','1',...args];const r=spawnSync(bin,all,{shell:false,timeout:15000,killSignal:'SIGKILL',maxBuffer:8*1024*1024});commands.push({args:all,status:r.status,signal:r.signal,stdoutBytes:r.stdout?.length||0,stderrTail:r.stderr?.toString().slice(-1800)||'',error:r.error?.message||null});if(!allowFailure)ensure(!r.error&&r.status===0,`FFMPEG:${r.error?.message||r.stderr?.toString().slice(-900)}`);return r;};
 h.decode=(file,w,hgt)=>{const r=h.ff(['-xerror','-err_detect','explode','-i',file,'-map','0:v:0','-an','-pix_fmt','rgb24','-f','rawvideo','pipe:1']);ensure(r.stdout.length>0&&r.stdout.length%(w*hgt*3)===0,'DECODE_GEOMETRY');return r.stdout;};
 let fatal=null;let ffmpeg=null;
 try{if(media){const r=h.ff(['-version']);ffmpeg={version:r.stdout.toString().split('\n')[0],binarySha256:path.isAbsolute(bin)?sha(fs.readFileSync(bin)):null};}await fn(h);ensure(tests.length>=6,'AT_LEAST_SIX_CHECKS');}
 catch(e){fatal=e.stack||String(e);process.exitCode=1;}
 finally{fs.rmSync(tmp,{recursive:true,force:true});const scriptsAfter=Object.fromEntries(Object.keys(scripts).map(n=>[n,sha(fs.readFileSync(path.join(here,n)))]));if(JSON.stringify(scriptsAfter)!==JSON.stringify(scripts)){fatal='SCRIPT_CHANGED_DURING_RUN';process.exitCode=1;}
 const receipt={task,recordedAt:new Date().toISOString(),nodeVersion:process.version,ffmpeg,scriptHashes:scripts,scriptBindingVerified:JSON.stringify(scriptsAfter)===JSON.stringify(scripts),fixtureOnly:true,providerModelTest:false,productionTaskRun:false,networkScope:'loopback-only or no network',passed:!fatal,checks:tests,observations:h.info,commands,fatal};json(h.p('execution-receipt.json'),receipt);json(h.p('failure-receipt.json'),{task,expectedFailureChecks:failures});fs.writeFileSync(h.p('checks.csv'),'check,result,expected_rejection\n'+tests.map(t=>`${t.name},${t.passed?'pass':'fail'},${Boolean(t.expectedRejection)}`).join('\n')+'\n');console.log(JSON.stringify({task,passed:!fatal,checks:tests.length,expectedRejections:failures.length,out}));if(fatal)console.error(fatal);}
}

run-recipe.mjs

import {fs,json,ensure,run} from './common.mjs';
await run('subtitle-cue-timing-validation',async h=>{
 const valid='1\n00:00:00,000 --> 00:00:00,700\nOpen the lid.\n\n2\n00:00:00,700 --> 00:00:01,400\nShow the hinge.\n\n3\n00:00:01,500 --> 00:00:02,000\nHold the final view.\n';fs.writeFileSync(h.p('valid.srt'),valid);json(h.p('duration.json'),{durationMilliseconds:2000,policy:'no overlap; adjacency allowed; inclusive final media boundary'});
 const validate=text=>{const blocks=text.trim().split(/\r?\n\r?\n/);let previousEnd=0;return blocks.map((block,i)=>{const lines=block.split(/\r?\n/);ensure(lines[0]===String(i+1),'CUE_SEQUENCE');const m=lines[1]?.match(/^(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})$/);ensure(m,'TIMESTAMP_SYNTAX');const ms=offset=>{const n=m.slice(offset,offset+4).map(Number);ensure(n[1]<60&&n[2]<60,'TIME_COMPONENT');return ((n[0]*60+n[1])*60+n[2])*1000+n[3];};const start=ms(1),end=ms(5);ensure(end>start,'ZERO_OR_REVERSED_DURATION');ensure(start>=previousEnd,'OVERLAP');ensure(end<=2000,'PAST_MEDIA_BOUNDARY');ensure(lines.slice(2).join('\n').trim().length>0,'EMPTY_CAPTION');previousEnd=end;return{index:i+1,startMilliseconds:start,endMilliseconds:end};});};const cues=validate(valid);json(h.p('cue-table.json'),cues);h.check('three-cues-accepted',cues.length===3);h.check('adjacent-boundary-allowed',cues[1].startMilliseconds===cues[0].endMilliseconds);h.check('final-media-boundary-allowed',cues[2].endMilliseconds===2000);
 const cases=[['overlap',valid.replace('00:00:00,700 --> 00:00:01,400','00:00:00,600 --> 00:00:01,400'),/OVERLAP/],['zero-duration',valid.replace('00:00:01,500 --> 00:00:02,000','00:00:01,500 --> 00:00:01,500'),/ZERO_OR_REVERSED_DURATION/],['past-boundary',valid.replace('00:00:02,000','00:00:02,001'),/PAST_MEDIA_BOUNDARY/],['wrong-cue-index',valid.replace('\n\n2\n','\n\n4\n'),/CUE_SEQUENCE/],['bad-milliseconds',valid.replace('00:00:00,000','00:00:00,00'),/TIMESTAMP_SYNTAX/],['invalid-minute',valid.replace('00:00:01,500','00:60:01,500'),/TIME_COMPONENT/]];for(const[name,text,pattern]of cases){fs.writeFileSync(h.p(`invalid-${name}.srt`),text);h.reject(`${name}-rejected`,()=>validate(text),pattern);}h.info={mediaDurationMilliseconds:2000,cueCount:cues.length,fontRenderingTest:false,burnInTest:false,policy:'strict fixture SRT subset; no HTML/font/reading-speed verification'};
});

Technical references

Validate SRT cue overlap, duration and media boundaries — Original task diagram; not a model output
Original task diagram; not a model output
Validate SRT cue overlap, duration and media boundaries