CJK subtitle burn-in: font coverage, UTF-8 checks and decoded-frame review
Run an original 3.6-second caption exercise with a licensed pinned Noto CJK font, a dependency-free cmap checker, real FFmpeg/libass rendering, four decoded frames and 29 executed checks. Separate missing-glyph checks from readable, regionally correct text.
Before finishing a captioned clip, distinguish four different failures: incorrect subtitle bytes, a font without the requested codepoint, a renderer using another face, and pixels that do not match the intended text. This recipe supplies a real local execution sample, not a MiniMax model test.
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 the three modules and sample.srt below in one empty folder, preserving UTF-8 text. The renderer creates its own geometric source video. Its one external data prerequisite is the exact, locally held font specified below; the preflight intentionally rejects a missing or different font. Run preflight before rendering, from this folder.
- Save the three complete Node scripts and UTF-8 sample.srt below in the same folder. Supply your own already licensed, unmodified NotoSansCJKsc-Regular.otf (Sans 2.004) there; its required SHA-256 is 2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b. Keep its OFL and copyright notices if you redistribute the font.
- Use Node.js 24 and an existing FFmpeg 6.0 build with libass/libx264; use your existing local FFmpeg installation. The recorded run used Node v24.14.0, libass 0.17.0 and Noto font 2.004.
- Choose a fresh local output folder. The sample is silent, 1280×720 and 3.6 seconds long; its script is not a full-length delivery exporter.
- Read the intended four cues before rendering. An SC font’s nonzero glyph mappings do not establish preferred Japanese, Korean or Traditional Chinese regional forms.
01. Preserve the exact font and verify the subtitle text
Use the locally supplied NotoSansCJKsc-Regular.otf and retain its existing license notices. The unmodified official Sans2.004 font is pinned by SHA-256 and font name. Open sample.srt as UTF-8 and check its four cue texts and time ranges before any renderer is involved. The parser deliberately rejects markup, overlapping cues and variation sequences; it does not guess an unknown encoding or silently rewrite the subtitle. SRT start/end boundaries must align to 10 ms because ASS stores centiseconds; finer values are refused rather than rounded.
node --version
node run-preflight-tests.mjs
02. Treat codepoint coverage as one preflight result
subtitle-check.mjs reads the font’s Unicode cmap format 4 or 12 and checks nonzero, in-range glyph IDs. This sample contains 43 unique non-whitespace codepoints and none were missing. Twenty-two executed scenarios include a known absent codepoint, missing or modified fonts, invalid UTF-8/UTF-16, overlap, unsafe paths and argument boundaries. Coverage is not a shaping or typography proof: a different regional glyph or unreadable layout can still have a valid mapping.
03. Run the actual burn-in with safe fixed filter filenames
Pass an absolute FFmpeg binary path and a fresh output directory. The runner creates an original geometric slate, converts supported plaintext SRT into a fixed-style ASS file and uses libass to burn it in. User paths are copied to constant staging filenames instead of being interpolated into a filter expression. Child processes use shell:false, one encoder/filter thread, bounded logs and a one-minute timeout. The recorded macOS font provider was CoreText; the log confirms loading the locally supplied pinned font and selecting its PostScript face, without claiming general font isolation.
node run-recipe.mjs --ffmpeg /absolute/path/to/ffmpeg --out ./fresh-output
node run-recipe.mjs --ffmpeg /absolute/path/to/ffmpeg --out ./another-fresh-output --input ./fresh-output/sample-source.mp4 --srt ./sample.srt --font ./NotoSansCJKsc-Regular.otf
04. Decode and read the text, then keep the execution receipt
Compare keyframe-01 through keyframe-04 to the intended bilingual, Simplified/Traditional Chinese and Japanese/Korean cues. The script decodes each PNG and measures subtitle-band pixel changes against the uncaptioned source; those measurements do not prove character identity. Also read the actual font-selection log and coverage report. The execution receipt includes seven media assertions, twenty-two preflight scenarios, file sizes, hashes and the exact tool versions. A limited visual readback was recorded, while regional typography and other subtitle text still need their own review.
Acceptance
- sample.srt decodes strictly as UTF-8 and has valid, ordered, nonoverlapping cue times; the twenty-two preflight tests pass.
- The locally supplied pinned font remains byte-for-byte matched to its pinned SHA-256, and its OFL license plus copyright notice travel with it.
- All 43 non-whitespace sample codepoints map to valid nonzero glyph IDs; no all-Unicode or regional-form coverage claim is inferred.
- Actual FFmpeg rendering succeeds and its log records the pinned Noto face; missing-glyph diagnostics and unconfirmed font selection fail the run.
- All four selected output frames are decoded at their intended cue times and have measured subtitle-band differences from the clean source.
- The expected text is checked visually for replacement boxes, clipping and punctuation; a nonempty PNG or pixel delta alone is insufficient.
- The receipt identifies actual versions and output hashes, states that production/provider tasks were not run, and preserves the distinction between local rendering and generation-quality evidence.
Troubleshooting
The text contains replacement symbols before rendering.
Export the source subtitle explicitly as UTF-8 and rerun preflight. Do not change an encoding label while leaving unknown bytes unchanged.
Coverage finds a missing U+ codepoint.
Inspect the exact codepoint, obtain a suitably licensed font covering it, and redo the family name, checksum, renderer and visual checks. Do not accept an undocumented system fallback.
Glyphs exist but look wrong for the target language.
Separate default codepoint coverage from region-specific CJK forms. Use the appropriate language variant and have the intended language’s typography reviewed; the SC sample does not prove those regional forms.
The renderer exits successfully but the visible subtitle is absent or clipped.
Read actual cue times, font-selection diagnostics and decoded frames. Check the 1280×720/3.6-second demonstration limits and placement before adapting the script to a real clip.
A path, font or output-file check rejects the command.
Use a fresh controlled directory, the exact pinned local font, ordinary local files and an absolute FFmpeg path. The script refuses overwrite, symlinks, traversal and network inputs.
The fixture works but a full delivery would lose audio or content after 3.6 seconds.
Do not use this sample runner unchanged for full delivery. Review duration, audio mapping, frame size and caption safe area in a separately verified export command.
A 201–209 ms cue is refused before conversion.
Use 10 ms-aligned start/end boundaries with a positive duration. This sample does not round millisecond boundaries, because both values would otherwise collapse to 0.20 seconds in ASS.
Keep with the result
Keep the source subtitle, exact font/license, renderer log, four decoded sample frames and execution receipt together. The recorded hashes identify their particular local run; platform/build differences can change output bytes. No model generation, production billing or search-traffic result is claimed.
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.
run-preflight-tests.mjs
#!/usr/bin/env node
import assert from 'node:assert/strict';
import {readFile,writeFile,mkdtemp,rm,symlink} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join,dirname} from 'node:path';
import {fileURLToPath} from 'node:url';
import {createHash} from 'node:crypto';
import {parseSrt,inspectFont,localFile,makeAss,SubtitleError} from './subtitle-check.mjs';
import {burnSubtitles,cliOptions} from './run-recipe.mjs';
const base=dirname(fileURLToPath(import.meta.url)),folder=await mkdtemp(join(tmpdir(),'cjk-preflight-'));
const font=await readFile(join(base,'NotoSansCJKsc-Regular.otf')),srt=await readFile(join(base,'sample.srt'));
const scenarios=[];const error=code=>exception=>exception instanceof SubtitleError&&exception.code===code;
function check(name,test){test();scenarios.push({name,passed:true});}
async function checkAsync(name,test){await test();scenarios.push({name,passed:true});}
const absentBinary='/never-executed-ffmpeg-in-negative-preflight-tests';
try{
check('valid-four-cue-UTF8-and-CJK-cmap',()=>{const parsed=parseSrt(srt);assert.equal(parsed.cues.length,4);assert.equal(inspectFont(font,parsed.codepoints).missing.length,0);});
check('known-missing-codepoint-detected',()=>{const result=inspectFont(font,[0x10fffd]);assert.equal(result.missing[0].codepoint,'U+10FFFD');});
check('invalid-UTF8-rejected',()=>assert.throws(()=>parseSrt(Buffer.from([0xc3,0x28])),error('invalid_utf8')));
check('UTF16-BOM-rejected',()=>assert.throws(()=>parseSrt(Buffer.from([0xff,0xfe,0x31,0])),error('invalid_utf8')));
check('NUL-control-rejected',()=>assert.throws(()=>parseSrt(Buffer.from(srt.toString()+'\0')),error('invalid_text_control')));
check('timestamp-minute-range-rejected',()=>assert.throws(()=>parseSrt(Buffer.from(srt.toString().replace('00:00:00,200','00:99:00,200'))),error('subtitle_timestamp')));
check('non-centisecond-SRT-boundaries-rejected',()=>assert.throws(()=>parseSrt(Buffer.from(srt.toString().replace('00:00:00,200 --> 00:00:00,950','00:00:00,201 --> 00:00:00,209'))),error('subtitle_precision_not_supported')));
check('collapsed-ASS-range-rejected',()=>assert.throws(()=>makeAss([{startMs:201,endMs:209,text:'字幕'}]),error('subtitle_precision_not_supported')));
check('overlapping-cues-rejected',()=>assert.throws(()=>parseSrt(Buffer.from(srt.toString().replace('00:00:01,000','00:00:00,900'))),error('subtitle_overlap_or_duration')));
check('ASS-and-HTML-markup-refused',()=>assert.throws(()=>parseSrt(Buffer.from(srt.toString().replace('简体:','<i>简体:</i>'))),error('subtitle_markup_refused')));
check('variation-sequence-refused',()=>assert.throws(()=>parseSrt(Buffer.from(srt.toString().replace('字幕',String.fromCodePoint(0x79b0,0xe0100)))),error('unsupported_variation_sequence')));
check('truncated-font-refused',()=>assert.throws(()=>inspectFont(font.subarray(0,50),[0x4e00]),error('font_table_bounds')));
check('CLI-option-value-boundary',()=>assert.throws(()=>cliOptions(['--ffmpeg','--out','here']),error('invalid_arguments')));
check('CLI-duplicate-options-refused',()=>assert.throws(()=>cliOptions(['--ffmpeg','/one','--ffmpeg','/two','--out','here']),error('invalid_arguments')));
await checkAsync('missing-font-file-refused',()=>assert.rejects(burnSubtitles({ffmpeg:absentBinary,out:join(folder,'missing'),font:join(folder,'not-there.otf')}),error('missing_input_file')));
await checkAsync('font-symlink-refused',async()=>{const path=join(folder,'font-link.otf');await symlink(join(base,'NotoSansCJKsc-Regular.otf'),path);await assert.rejects(localFile(path,25*1024*1024),error('unsafe_input_file'));});
await checkAsync('input-path-traversal-refused',()=>assert.rejects(localFile('../escape.srt',65536),error('unsafe_input_path')));
await checkAsync('network-input-refused',()=>assert.rejects(localFile('https://example.invalid/subtitle.srt',65536),error('unsafe_input_path')));
await checkAsync('output-path-traversal-refused',()=>assert.rejects(burnSubtitles({ffmpeg:absentBinary,out:'../escape-output'}),error('unsafe_output_path')));
await checkAsync('missing-glyph-stops-before-FFmpeg',async()=>{const path=join(folder,'missing-glyph.srt');await writeFile(path,srt.toString().replace('字幕',String.fromCodePoint(0x10fffd)));await assert.rejects(burnSubtitles({ffmpeg:absentBinary,out:join(folder,'glyph'),srt:path}),error('missing_glyph'));});
await checkAsync('pinned-font-hash-drift-refused',async()=>{const path=join(folder,'changed-font.otf');const altered=Buffer.from(font);altered[10]^=1;await writeFile(path,altered);await assert.rejects(burnSubtitles({ffmpeg:absentBinary,out:join(folder,'drift'),font:path}),error('font_hash_mismatch'));});
await checkAsync('special-filename-is-data-not-shell',async()=>{const path=join(folder,"subtitle ' $(not-a-command); test.srt");await writeFile(path,srt);assert.equal(parseSrt(await localFile(path,65536)).cues.length,4);});
await writeFile(join(base,'preflight-test-receipt.json'),JSON.stringify({schemaVersion:1,blueprintId:'blueprint-28',executedAt:new Date().toISOString(),nodeVersion:process.version,passed:true,scenarioCount:scenarios.length,scenarios,negativeTestFFmpegExecutions:0,productionTaskRun:false,externalNetworkRequests:0,scriptHashes:Object.fromEntries(await Promise.all(['subtitle-check.mjs','run-recipe.mjs','run-preflight-tests.mjs'].map(async name=>[name,createHash('sha256').update(await readFile(join(base,name))).digest('hex')]))),limitation:'These tests validate preflight guards; they do not validate typography or provider model output.'},null,2)+'\n');
console.log(`Passed ${scenarios.length} preflight scenarios; no negative case spawned FFmpeg.`);
}finally{await rm(folder,{recursive:true,force:true});}
run-recipe.mjs
#!/usr/bin/env node
// Local media processing only; no provider/API calls and no shell interpolation.
import {spawn} from 'node:child_process';
import {readFile,writeFile,mkdir,mkdtemp,rm,copyFile,link,lstat,realpath} from 'node:fs/promises';
import {dirname,resolve,join} from 'node:path';
import {fileURLToPath,pathToFileURL} from 'node:url';
import {createHash} from 'node:crypto';
import {parseSrt,inspectFont,localFile,makeAss,SubtitleError} from './subtitle-check.mjs';
const base=dirname(fileURLToPath(import.meta.url));
const FONT_HASH='2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b';
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
const need=(condition,code)=>{if(!condition)throw new SubtitleError(code);};
const safeOutput=async path=>{need(typeof path==='string'&&path.length>0&&!path.includes(String.fromCharCode(0))&&!path.replaceAll(String.fromCharCode(92),'/').split('/').includes('..'),'unsafe_output_path');const full=resolve(path);await mkdir(full,{recursive:true,mode:0o700});const stat=await lstat(full);need(stat.isDirectory()&&!stat.isSymbolicLink(),'unsafe_output_directory');return realpath(full);};
const absent=async path=>{try{await lstat(path);throw new SubtitleError('output_exists');}catch(error){if(error.code!=='ENOENT')throw error;}};
const shared=['-hide_banner','-nostdin','-threads','1','-filter_threads','1'];
export async function burnSubtitles({ffmpeg,out,input,srt=join(base,'sample.srt'),font=join(base,'NotoSansCJKsc-Regular.otf')}){
need(typeof ffmpeg==='string'&&ffmpeg.startsWith('/')&&!ffmpeg.includes(String.fromCharCode(0))&&!ffmpeg.startsWith('-'),'missing_ffmpeg_path');
const parsed=parseSrt(await localFile(srt,65536));const fontBytes=await localFile(font,25*1024*1024);
need(sha(fontBytes)===FONT_HASH,'font_hash_mismatch');const coverage=inspectFont(fontBytes,parsed.codepoints);
need(coverage.missing.length===0,'missing_glyph');need(coverage.fontNames.some(name=>name.id===1&&name.value==='Noto Sans CJK SC'),'font_family_mismatch');
if(input)await localFile(input,25*1024*1024);
const output=await safeOutput(out);const names=['sample-source.mp4','subtitle-burned.mp4','sample.ass','coverage-report.json','command-log.json','ffmpeg-log.txt','execution-receipt.json','keyframe-01.png','keyframe-02.png','keyframe-03.png','keyframe-04.png'];
for(const name of names)await absent(join(output,name));
const stage=await mkdtemp(join(output,'.subtitle-stage-'));const commands=[];const logs=[];
const execute=(args,limit=1048576)=>new Promise((done,fail)=>{
const child=spawn(ffmpeg,args,{cwd:stage,shell:false,env:{...process.env,FONTCONFIG_FILE:join(stage,'fonts.conf'),FONTCONFIG_PATH:stage}});
const stdout=[];let stdoutBytes=0,stderr='';let failed=false;
const timer=setTimeout(()=>{failed=true;child.kill('SIGKILL');},60000);
child.stdout.on('data',chunk=>{stdoutBytes+=chunk.length;if(stdoutBytes>limit){failed=true;child.kill('SIGKILL');}else stdout.push(chunk);});
child.stderr.on('data',chunk=>{if(Buffer.byteLength(stderr)+chunk.length>1048576){failed=true;child.kill('SIGKILL');}else stderr+=chunk.toString('utf8');});
child.once('error',error=>{clearTimeout(timer);fail(new SubtitleError('ffmpeg_spawn_failed'));});
child.once('close',code=>{clearTimeout(timer);commands.push({program:'ffmpeg',args,exitCode:code,stdoutBytes,stderrBytes:Buffer.byteLength(stderr)});logs.push(stderr);if(failed||code!==0){fail(new SubtitleError(failed?'ffmpeg_budget_exceeded':'ffmpeg_failed'));return;}done({stdout:Buffer.concat(stdout),stderr});});
});
try{
const version=await execute(['-version']);const versionText=version.stdout.toString('utf8');need(/^ffmpeg version 6\.0(?: |$)/m.test(versionText),'ffmpeg_version_mismatch');
await mkdir(join(stage,'fonts'));await writeFile(join(stage,'fonts','font.otf'),fontBytes);
await writeFile(join(stage,'fonts.conf'),'<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig><dir>fonts</dir><cachedir>font-cache</cachedir></fontconfig>');
await writeFile(join(stage,'subtitles.ass'),makeAss(parsed.cues));
if(input)await copyFile(input,join(stage,'input.mp4'));
else await execute([...shared,'-f','lavfi','-i','color=c=0x0b1726:size=1280x720:rate=24,drawbox=x=80:y=100:w=1120:h=410:color=0x12334c:t=fill,drawbox=x=150:y=200:w=300:h=200:color=0x40ccb2:t=fill,drawbox=x=650:y=230:w=320:h=140:color=0xf2aa69:t=fill','-t','3.6','-an','-c:v','libx264','-preset','veryfast','-crf','18','-pix_fmt','yuv420p','-threads','1','input.mp4']);
const burn=await execute([...shared,'-loglevel','verbose','-i','input.mp4','-vf','ass=subtitles.ass:fontsdir=fonts','-t','3.6','-an','-c:v','libx264','-preset','veryfast','-crf','18','-pix_fmt','yuv420p','-threads','1','burned.mp4']);
need(!/Glyph 0x[0-9A-F]+ not found|fontselect: failed/i.test(burn.stderr),'renderer_missing_glyph');
need(/fontselect:.*NotoSansCJKsc-Regular/.test(burn.stderr),'font_selection_unconfirmed');
const times=[0.6,1.4,2.2,3.0];const frameChecks=[];
for(let i=0;i<times.length;i++){
const stamp=String(times[i]);const name=`keyframe-${String(i+1).padStart(2,'0')}.png`;
await execute([...shared,'-ss',stamp,'-i','burned.mp4','-frames:v','1','-threads','1','-update','1',name]);
const args=input=>[...shared,'-ss',stamp,'-i',input,'-vf','crop=1280:120:0:600,format=rgb24','-frames:v','1','-f','rawvideo','pipe:1'];
const clean=await execute(args('input.mp4'));const rendered=await execute(args('burned.mp4'));
need(clean.stdout.length===1280*120*3&&rendered.stdout.length===clean.stdout.length,'decoded_frame_size');
let changed=0,total=0;for(let at=0;at<clean.stdout.length;at+=3){let pixel=false;for(let channel=0;channel<3;channel++){const delta=Math.abs(clean.stdout[at+channel]-rendered.stdout[at+channel]);total+=delta;if(delta>16)pixel=true;}if(pixel)changed++;}
need(changed>500,'no_visible_subtitle_difference');frameChecks.push({atSeconds:times[i],png:name,subtitleBand:{x:0,y:600,width:1280,height:120},changedPixelsWithChannelDeltaOver16:changed,meanAbsoluteChannelDelta:total/clean.stdout.length,claim:'Decoded pixels changed in the subtitle band; this alone does not establish character correctness.'});
}
const emitted=['sample-source.mp4','subtitle-burned.mp4','sample.ass',...times.map((_,i)=>`keyframe-${String(i+1).padStart(2,'0')}.png`)];
const sourceMap={'sample-source.mp4':'input.mp4','subtitle-burned.mp4':'burned.mp4','sample.ass':'subtitles.ass'};const hashes={};
for(const name of emitted){const file=sourceMap[name]||name;const bytes=await readFile(join(stage,file));need(bytes.length<=64*1024*1024,'output_size_limit');hashes[name]={sha256:sha(bytes),bytes:bytes.length};}
const receipt={schemaVersion:1,blueprintId:'blueprint-28',evidenceClass:'local-media-run',executedAt:new Date().toISOString(),nodeVersion:process.version,ffmpegVersion:versionText.split('\n')[0],ffmpegBinarySha256:sha(await readFile(ffmpeg)),fontSha256:sha(fontBytes),fontVersion:coverage.fontNames.find(name=>name.id===5)?.value,productionTaskRun:false,providerModelTest:false,externalNetworkRequests:0,
sourceClip:input?'Operator-supplied local clip':'Original synthetic colored geometric slate generated with lavfi; no model output',cues:parsed.cues,coverage:{checkedCodepoints:coverage.checkedCodepoints,missing:coverage.missing,cmap:coverage.cmap},fontSelectionLog:burn.stderr.split('\n').filter(line=>/fontselect|font provider|libass API|libass source|Shaper|Loading font/.test(line)),frameChecks,outputs:hashes,
passedScenarios:['strict-UTF8-SRT-preflight','pinned-font-cmap-coverage','bounded-actual-libass-burnin','font-selection-observed','four-keyframes-decoded','four-subtitle-band-pixel-differences','media-and-frame-output-hashes'],
limitations:['Cmap checks default glyph indexes only; regional CJK forms, variation sequences, kerning and shaping need additional validation.','Decoded pixel differences and nonempty PNGs do not prove characters are correct; compare actual frames to the intended text.','This run contains no MiniMax/provider generation, production API, billing or output-quality test.']};
await writeFile(join(stage,'coverage-report.json'),JSON.stringify(coverage,null,2)+'\n');await writeFile(join(stage,'command-log.json'),JSON.stringify(commands,null,2)+'\n');await writeFile(join(stage,'ffmpeg-log.txt'),logs.join('\n--- command boundary ---\n'));
await writeFile(join(stage,'execution-receipt.json'),JSON.stringify(receipt,null,2)+'\n');
for(const name of names){const source=sourceMap[name]||name;await link(join(stage,source),join(output,name));}
return receipt;
}finally{await rm(stage,{recursive:true,force:true});}
}
export function cliOptions(args){
const flags=new Set(['--ffmpeg','--out','--input','--srt','--font']);const options={};
for(let i=0;i<args.length;i+=2){need(flags.has(args[i])&&typeof args[i+1]==='string'&&args[i+1].length>0&&!args[i+1].startsWith('--')&&!Object.hasOwn(options,args[i].slice(2)),'invalid_arguments');options[args[i].slice(2)]=args[i+1];}
need(options.ffmpeg&&options.out,'missing_arguments');return options;
}
if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href){
Promise.resolve().then(()=>burnSubtitles(cliOptions(process.argv.slice(2)))).then(receipt=>console.log(JSON.stringify({passed:true,cues:receipt.cues.length,ffmpegVersion:receipt.ffmpegVersion,productionTaskRun:false}))).catch(error=>{console.error(error instanceof SubtitleError?error.code:'recipe_failed');process.exitCode=1;});
}
sample.srt
1
00:00:00,200 --> 00:00:00,950
字幕安全检查 / Subtitle check
2
00:00:01,000 --> 00:00:01,750
简体:蒸汽轻轻升起
3
00:00:01,800 --> 00:00:02,550
繁體:蒸氣緩緩升起
4
00:00:02,600 --> 00:00:03,350
日本語:静かな夜 한국어: 고요한 밤
subtitle-check.mjs
// Dependency-free UTF-8/SRT and OpenType cmap 4/12 preflight.
import { readFile, lstat } from 'node:fs/promises';
export class SubtitleError extends Error { constructor(code) {super(code);this.code=code;} }
const need=(condition,code)=>{if(!condition)throw new SubtitleError(code);};
const read16=(bytes,at)=>{need(at>=0&&at+2<=bytes.length,'font_table_bounds');return bytes.readUInt16BE(at);};
const read32=(bytes,at)=>{need(at>=0&&at+4<=bytes.length,'font_table_bounds');return bytes.readUInt32BE(at);};
export function decodeUtf8(bytes){try{return new TextDecoder('utf-8',{fatal:true}).decode(bytes).replace(/^\uFEFF/,'');}catch{throw new SubtitleError('invalid_utf8');}}
export function parseSrt(bytes){
need(bytes.length<=65536,'subtitle_too_large');const text=decodeUtf8(bytes).replaceAll('\r\n','\n');
need(!text.includes('\r')&&!text.includes('\0'),'invalid_text_control');
const blocks=text.trim().split(/\n\s*\n/);need(blocks.length>0&&blocks.length<=32,'subtitle_cue_limit');
let end=0;const cues=blocks.map((block,index)=>{
const lines=block.split('\n');need(lines[0]===String(index+1),'subtitle_sequence');
const match=/^(\d{2}):(\d{2}):(\d{2}),(\d{3}) --> (\d{2}):(\d{2}):(\d{2}),(\d{3})$/.exec(lines[1]||'');
need(match,'subtitle_timestamp');
const ms=offset=>{const parts=match.slice(offset,offset+4).map(Number);need(parts[0]<1&&parts[1]<60&&parts[2]<60,'subtitle_timestamp');return parts[0]*3600000+parts[1]*60000+parts[2]*1000+parts[3];};
const start=ms(1),stop=ms(5);need(start>=end&&stop>start&&stop<=60000,'subtitle_overlap_or_duration');need(start%10===0&&stop%10===0,'subtitle_precision_not_supported');end=stop;
const body=lines.slice(2);need(body.length>0&&body.length<=2&&body.every(line=>line.trim()&&[...line].length<=64),'subtitle_line_limit');
const content=body.join('\n');need(!/[{}<>]/u.test(content)&&!content.includes(String.fromCharCode(92)),'subtitle_markup_refused');
need(!/[\u200d\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/u.test(content),'unsupported_variation_sequence');
return {startMs:start,endMs:stop,text:content};
});
return {text,cues,codepoints:[...new Set(cues.flatMap(cue=>[...cue.text].filter(character=>!/[\s]/u.test(character)).map(character=>character.codePointAt(0))))].sort((a,b)=>a-b)};
}
export function inspectFont(bytes,codepoints){
need(bytes.length>=12&&bytes.length<=25*1024*1024,'invalid_font_size');need(bytes.toString('ascii',0,4)==='OTTO'||read32(bytes,0)===0x00010000,'unsupported_font_container');
const count=read16(bytes,4);need(count>0&&count<256,'invalid_font_tables');const tables=new Map();
for(let i=0;i<count;i++){const at=12+i*16;need(at+16<=bytes.length,'font_table_bounds');const tag=bytes.toString('ascii',at,at+4),offset=read32(bytes,at+8),length=read32(bytes,at+12);need(offset+length<=bytes.length,'font_table_bounds');tables.set(tag,bytes.subarray(offset,offset+length));}
const cmap=tables.get('cmap');need(cmap,'missing_cmap');const subtables=[];
for(let i=0;i<read16(cmap,2);i++){const at=4+i*8,platform=read16(cmap,at),encoding=read16(cmap,at+2),offset=read32(cmap,at+4);if(!(platform===0||platform===3&&(encoding===1||encoding===10)))continue;const format=read16(cmap,offset);if(format===12||format===4)subtables.push({format,offset,platform,encoding});}
subtables.sort((a,b)=>b.format-a.format||b.platform-a.platform);need(subtables.length>0,'unsupported_cmap');const chosen=subtables[0],base=chosen.offset;
let glyph;
if(chosen.format===12){const length=read32(cmap,base+4),groups=read32(cmap,base+12);need(base+length<=cmap.length&&16+groups*12<=length,'font_table_bounds');glyph=cp=>{let lo=0,hi=groups-1;while(lo<=hi){const mid=(lo+hi)>>1,at=base+16+mid*12,start=read32(cmap,at),end=read32(cmap,at+4);if(cp<start)hi=mid-1;else if(cp>end)lo=mid+1;else return read32(cmap,at+8)+cp-start;}return 0;};}
else{const length=read16(cmap,base+2),segments=read16(cmap,base+6)/2;need(Number.isInteger(segments)&&segments>0&&base+length<=cmap.length,'font_table_bounds');glyph=cp=>{if(cp>65535)return 0;const ends=base+14,starts=ends+segments*2+2,deltas=starts+segments*2,ranges=deltas+segments*2;for(let i=0;i<segments;i++){if(cp>read16(cmap,ends+i*2))continue;if(cp<read16(cmap,starts+i*2))return 0;const delta=read16(cmap,deltas+i*2),range=read16(cmap,ranges+i*2);if(!range)return (cp+delta)&65535;const position=ranges+i*2+range+(cp-read16(cmap,starts+i*2))*2;need(position+2<=base+length,'font_table_bounds');const value=read16(cmap,position);return value?(value+delta)&65535:0;}return 0;};}
const maxp=tables.get('maxp');need(maxp,'missing_maxp');const glyphCount=read16(maxp,4);
const names=[];const name=tables.get('name');need(name,'missing_font_names');const records=read16(name,2),storage=read16(name,4);
for(let i=0;i<records;i++){const at=6+i*12,platform=read16(name,at),nameId=read16(name,at+6),length=read16(name,at+8),offset=read16(name,at+10);if(![0,1,2,4,5,6].includes(nameId)||![0,3].includes(platform))continue;need(storage+offset+length<=name.length&&length%2===0,'font_table_bounds');const raw=name.subarray(storage+offset,storage+offset+length);const swapped=Buffer.from(raw);swapped.swap16();names.push({id:nameId,value:swapped.toString('utf16le')});}
const mappings=codepoints.map(cp=>{const id=glyph(cp);return {codepoint:`U+${cp.toString(16).toUpperCase().padStart(4,'0')}`,character:String.fromCodePoint(cp),glyphId:id,covered:id>0&&id<glyphCount};});
return {fontNames:[...new Map(names.map(row=>[`${row.id}:${row.value}`,row])).values()],cmap:{format:chosen.format,platform:chosen.platform,encoding:chosen.encoding},glyphCount,checkedCodepoints:codepoints.length,missing:mappings.filter(row=>!row.covered),mappings,
limitation:'A nonzero cmap mapping proves only a default glyph index in this font. It does not prove correct regional glyph form, shaping, layout, readable pixels, or fallback behavior.'};
}
export async function localFile(path,maxBytes){need(typeof path==='string'&&path.length>0&&!path.includes('\0')&&!/^\w+:\/\//.test(path)&&!path.replaceAll(String.fromCharCode(92),'/').split('/').includes('..'),'unsafe_input_path');let stat;try{stat=await lstat(path);}catch(error){if(error.code==='ENOENT')throw new SubtitleError('missing_input_file');throw error;}need(stat.isFile()&&!stat.isSymbolicLink()&&stat.size>0&&stat.size<=maxBytes,'unsafe_input_file');return readFile(path);}
export function makeAss(cues){
need(Array.isArray(cues)&&cues.every(cue=>Number.isSafeInteger(cue.startMs)&&Number.isSafeInteger(cue.endMs)&&cue.startMs%10===0&&cue.endMs%10===0&&cue.endMs>cue.startMs),'subtitle_precision_not_supported');
const stamp=ms=>`${Math.floor(ms/3600000)}:${String(Math.floor(ms/60000)%60).padStart(2,'0')}:${String(Math.floor(ms/1000)%60).padStart(2,'0')}.${String(Math.floor(ms%1000/10)).padStart(2,'0')}`;
return `[Script Info]\nScriptType: v4.00+\nPlayResX: 1280\nPlayResY: 720\nWrapStyle: 0\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Default,Noto Sans CJK SC,40,&H00FFFFFF,&H000000FF,&H00101010,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,50,50,45,1\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n`+cues.map(cue=>`Dialogue: 0,${stamp(cue.startMs)},${stamp(cue.endMs)},Default,,0,0,0,,${cue.text.replaceAll('\n','\\N')}`).join('\n')+'\n';
}
Technical references
