mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
fix(subsync): harden subtitle parsing, sign heuristics, and ffmpeg extraction
- shift signs and songs with the dialogue line nearest in time, not in file order - keep the BOM (and add one for non-UTF-8 sources) when rewriting in place - stop treating full tracks with songs and lines containing a music mark as signs - skip TTML tracks in local ffmpeg extraction (no decoder) - do not cache tracks that parsed to zero cues; cap retained ffmpeg stderr
This commit is contained in:
5 files changed
+283
-52
No files matched your search
@@ -190,3 +190,54 @@ test('cacheEmbeddedSubtitleTrack populates single-pass cache, ignores empty pars
|
|||||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('extractSinglePassRipMedia skips TTML tracks and does not cache empty tracks', async () => {
|
||||||
|
if (process.platform === 'win32') return;
|
||||||
|
clearAudioSpeechCache();
|
||||||
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-single-pass-'));
|
||||||
|
try {
|
||||||
|
const videoPath = path.join(tmpDir, 'episode.mkv');
|
||||||
|
const argsLog = path.join(tmpDir, 'args.log');
|
||||||
|
const ffmpegScript = path.join(tmpDir, 'ffmpeg.sh');
|
||||||
|
fs.writeFileSync(videoPath, 'video');
|
||||||
|
// Fake ffmpeg: track_2 gets one cue, track_5 parses to zero cues.
|
||||||
|
fs.writeFileSync(
|
||||||
|
ffmpegScript,
|
||||||
|
`#!/bin/sh
|
||||||
|
echo "$@" > "${argsLog}"
|
||||||
|
for arg in "$@"; do
|
||||||
|
case "$arg" in
|
||||||
|
*track_2.srt) printf '1\\n00:00:01,000 --> 00:00:02,000\\nHello\\n' > "$arg" ;;
|
||||||
|
*track_5.srt) : > "$arg" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
exit 0
|
||||||
|
`,
|
||||||
|
{ mode: 0o755 },
|
||||||
|
);
|
||||||
|
fs.chmodSync(ffmpegScript, 0o755);
|
||||||
|
|
||||||
|
const rip = await extractSinglePassRipMedia({
|
||||||
|
ffmpegPath: ffmpegScript,
|
||||||
|
videoPath,
|
||||||
|
audioStreamIndex: 1,
|
||||||
|
embeddedTracks: [
|
||||||
|
{ ffIndex: 2, extension: 'srt' },
|
||||||
|
{ ffIndex: 4, extension: 'ttml' },
|
||||||
|
{ ffIndex: 5, extension: 'srt' },
|
||||||
|
],
|
||||||
|
includeAudio: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.ok(rip !== null);
|
||||||
|
assert.ok(!fs.readFileSync(argsLog, 'utf8').includes('0:4'));
|
||||||
|
assert.equal(rip.embeddedSubtitles.get(2)?.events.length, 1);
|
||||||
|
assert.equal(rip.embeddedSubtitles.get(5)?.events.length, 0);
|
||||||
|
const cached = getCachedEmbeddedSubtitles(videoPath);
|
||||||
|
assert.equal(cached?.get(2)?.events.length, 1);
|
||||||
|
assert.equal(cached?.has(5), false);
|
||||||
|
} finally {
|
||||||
|
clearAudioSpeechCache();
|
||||||
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -9,7 +9,13 @@ import {
|
|||||||
type ParsedSubtitleFile,
|
type ParsedSubtitleFile,
|
||||||
type SubtitleTimeSpan,
|
type SubtitleTimeSpan,
|
||||||
} from './subtitle-lines';
|
} from './subtitle-lines';
|
||||||
import { extensionToFfmpegMuxer, fileExists, resolveCommandInvocation, runCommand } from './utils';
|
import {
|
||||||
|
canFfmpegExtractSubtitleExtension,
|
||||||
|
extensionToFfmpegMuxer,
|
||||||
|
fileExists,
|
||||||
|
resolveCommandInvocation,
|
||||||
|
runCommand,
|
||||||
|
} from './utils';
|
||||||
|
|
||||||
const PCM_VAD_SAMPLE_RATE = 8000;
|
const PCM_VAD_SAMPLE_RATE = 8000;
|
||||||
const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400';
|
const PCM_VAD_FILTER = 'highpass=f=200,lowpass=f=3400';
|
||||||
@@ -135,6 +141,14 @@ export function getCachedEmbeddedSubtitles(
|
|||||||
return cached && cached.size > 0 ? new Map(cached) : null;
|
return cached && cached.size > 0 ? new Map(cached) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ffmpeg stderr only feeds error messages; a corrupt file can spam megabytes of it.
|
||||||
|
const STDERR_TAIL_LIMIT = 64 * 1024;
|
||||||
|
|
||||||
|
function appendStderrTail(current: string, chunk: Buffer): string {
|
||||||
|
const next = current + chunk.toString();
|
||||||
|
return next.length > STDERR_TAIL_LIMIT ? next.slice(-STDERR_TAIL_LIMIT) : next;
|
||||||
|
}
|
||||||
|
|
||||||
export function cacheEmbeddedSubtitleTrack(
|
export function cacheEmbeddedSubtitleTrack(
|
||||||
videoPath: string,
|
videoPath: string,
|
||||||
ffIndex: number,
|
ffIndex: number,
|
||||||
@@ -378,7 +392,7 @@ function streamFfmpegPcm(
|
|||||||
chunks.push(chunk);
|
chunks.push(chunk);
|
||||||
});
|
});
|
||||||
child.stderr.on('data', (chunk: Buffer) => {
|
child.stderr.on('data', (chunk: Buffer) => {
|
||||||
stderr += chunk.toString();
|
stderr = appendStderrTail(stderr, chunk);
|
||||||
});
|
});
|
||||||
child.on('error', (error: Error) => {
|
child.on('error', (error: Error) => {
|
||||||
finishError(error);
|
finishError(error);
|
||||||
@@ -564,7 +578,7 @@ function spawnFfmpegWithStdout(
|
|||||||
chunks.push(chunk);
|
chunks.push(chunk);
|
||||||
});
|
});
|
||||||
child.stderr.on('data', (chunk: Buffer) => {
|
child.stderr.on('data', (chunk: Buffer) => {
|
||||||
stderr += chunk.toString();
|
stderr = appendStderrTail(stderr, chunk);
|
||||||
});
|
});
|
||||||
child.on('error', (error: Error) => {
|
child.on('error', (error: Error) => {
|
||||||
finishError(error);
|
finishError(error);
|
||||||
@@ -704,7 +718,10 @@ export async function extractSinglePassRipMedia(
|
|||||||
new Map<number, ParsedSubtitleFile>();
|
new Map<number, ParsedSubtitleFile>();
|
||||||
const cachedAudio = audioKey ? (audioSpeechCache.get(audioKey) ?? null) : null;
|
const cachedAudio = audioKey ? (audioSpeechCache.get(audioKey) ?? null) : null;
|
||||||
|
|
||||||
const missingTracks = options.embeddedTracks.filter((t) => !cachedSubs.has(t.ffIndex));
|
// A track ffmpeg cannot decode (TTML) would fail every output of the shared pass.
|
||||||
|
const missingTracks = options.embeddedTracks.filter(
|
||||||
|
(t) => !cachedSubs.has(t.ffIndex) && canFfmpegExtractSubtitleExtension(t.extension),
|
||||||
|
);
|
||||||
const needAudio = options.includeAudio && cachedAudio === null;
|
const needAudio = options.includeAudio && cachedAudio === null;
|
||||||
|
|
||||||
if (missingTracks.length === 0 && !needAudio) {
|
if (missingTracks.length === 0 && !needAudio) {
|
||||||
@@ -793,18 +810,22 @@ export async function extractSinglePassRipMedia(
|
|||||||
);
|
);
|
||||||
|
|
||||||
const updatedSubs = new Map<number, ParsedSubtitleFile>(cachedSubs);
|
const updatedSubs = new Map<number, ParsedSubtitleFile>(cachedSubs);
|
||||||
|
let cacheChanged = false;
|
||||||
for (const { ffIndex, outPath } of trackOutputs) {
|
for (const { ffIndex, outPath } of trackOutputs) {
|
||||||
if (!fileExists(outPath)) continue;
|
if (!fileExists(outPath)) continue;
|
||||||
try {
|
try {
|
||||||
const bytes = fs.readFileSync(outPath);
|
const bytes = fs.readFileSync(outPath);
|
||||||
const parsed = parseSubtitleFileContent(decodeSubtitleBytes(bytes), outPath);
|
const parsed = parseSubtitleFileContent(decodeSubtitleBytes(bytes), outPath);
|
||||||
updatedSubs.set(ffIndex, parsed);
|
updatedSubs.set(ffIndex, parsed);
|
||||||
|
// Like cacheEmbeddedSubtitleTrack: empty results are returned but never cached.
|
||||||
|
if (parsed.events.length > 0) cacheChanged = true;
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore individual unparseable track.
|
// Ignore individual unparseable track.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (updatedSubs.size > 0) {
|
if (cacheChanged) {
|
||||||
rememberLru(embeddedSubtitlesCache, fileKey, updatedSubs);
|
const cacheable = new Map([...updatedSubs].filter(([, parsed]) => parsed.events.length > 0));
|
||||||
|
rememberLru(embeddedSubtitlesCache, fileKey, cacheable);
|
||||||
}
|
}
|
||||||
|
|
||||||
let audioSpeech: AudioSpeechResult | null = options.includeAudio ? cachedAudio : null;
|
let audioSpeech: AudioSpeechResult | null = options.includeAudio ? cachedAudio : null;
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ test('isSignStyleOrEffect separates signs/songs styles from dialogue styles', ()
|
|||||||
'Main Top',
|
'Main Top',
|
||||||
'DefaultItalics',
|
'DefaultItalics',
|
||||||
'Edward',
|
'Edward',
|
||||||
|
'Ed',
|
||||||
|
'Op',
|
||||||
|
'TL',
|
||||||
|
'Caption',
|
||||||
]) {
|
]) {
|
||||||
assert.equal(isSignStyleOrEffect(dialogueStyle), false, `${dialogueStyle} should be dialogue`);
|
assert.equal(isSignStyleOrEffect(dialogueStyle), false, `${dialogueStyle} should be dialogue`);
|
||||||
}
|
}
|
||||||
@@ -38,6 +42,10 @@ test('isSignStyleOrEffect separates signs/songs styles from dialogue styles', ()
|
|||||||
'Insert Song',
|
'Insert Song',
|
||||||
'Lyrics',
|
'Lyrics',
|
||||||
'Typeset',
|
'Typeset',
|
||||||
|
'ED',
|
||||||
|
'看板',
|
||||||
|
'OP歌詞',
|
||||||
|
'タイトル',
|
||||||
]) {
|
]) {
|
||||||
assert.equal(isSignStyleOrEffect(signStyle), true, `${signStyle} should be a sign/song`);
|
assert.equal(isSignStyleOrEffect(signStyle), true, `${signStyle} should be a sign/song`);
|
||||||
}
|
}
|
||||||
@@ -50,6 +58,14 @@ test('isSignsOrSongsTrackMeta flags signs, songs, lyrics, and forced tracks', ()
|
|||||||
assert.equal(isSignsOrSongsTrackMeta({ 'external-filename': '/tmp/ep01.forced.ass' }), true);
|
assert.equal(isSignsOrSongsTrackMeta({ 'external-filename': '/tmp/ep01.forced.ass' }), true);
|
||||||
assert.equal(isSignsOrSongsTrackMeta({ title: 'English [Full Dialogue]' }), false);
|
assert.equal(isSignsOrSongsTrackMeta({ title: 'English [Full Dialogue]' }), false);
|
||||||
assert.equal(isSignsOrSongsTrackMeta({ title: 'Japanese' }), false);
|
assert.equal(isSignsOrSongsTrackMeta({ title: 'Japanese' }), false);
|
||||||
|
for (const fullTitle of [
|
||||||
|
'English (Full + Songs)',
|
||||||
|
'Dialogue & Songs',
|
||||||
|
'Full Subtitles [with lyrics]',
|
||||||
|
'日本語 (歌詞あり)',
|
||||||
|
]) {
|
||||||
|
assert.equal(isSignsOrSongsTrackMeta({ title: fullTitle }), false, fullTitle);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('parseSubtitleFileContent classifies ASS signs, drawings, karaoke, and preserves format on rewrite', () => {
|
test('parseSubtitleFileContent classifies ASS signs, drawings, karaoke, and preserves format on rewrite', () => {
|
||||||
@@ -157,7 +173,14 @@ test('parseSubtitleFileContent preserves SRT/VTT cue settings and strips music-o
|
|||||||
test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable bytes accurately', () => {
|
test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable bytes accurately', () => {
|
||||||
const bomBytes = new Uint8Array([0xef, 0xbb, 0xbf, ...Buffer.from('hello', 'utf8')]);
|
const bomBytes = new Uint8Array([0xef, 0xbb, 0xbf, ...Buffer.from('hello', 'utf8')]);
|
||||||
assert.equal(decodeSubtitleBytes(bomBytes), 'hello');
|
assert.equal(decodeSubtitleBytes(bomBytes), 'hello');
|
||||||
assert.deepEqual(decodeSubtitleBytesWithStatus(bomBytes), { text: 'hello', lossless: true });
|
assert.deepEqual(decodeSubtitleBytesWithStatus(bomBytes), {
|
||||||
|
text: '\uFEFFhello',
|
||||||
|
lossless: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(decodeSubtitleBytesWithStatus(Buffer.from('hello', 'utf8')), {
|
||||||
|
text: 'hello',
|
||||||
|
lossless: true,
|
||||||
|
});
|
||||||
|
|
||||||
// Bytes invalid in UTF-8, Shift_JIS, and EUC-JP trigger lossy fallback.
|
// Bytes invalid in UTF-8, Shift_JIS, and EUC-JP trigger lossy fallback.
|
||||||
const corrupt = new Uint8Array([0x80, 0xff, 0xfe, 0x80]);
|
const corrupt = new Uint8Array([0x80, 0xff, 0xfe, 0x80]);
|
||||||
@@ -171,7 +194,10 @@ test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable b
|
|||||||
|
|
||||||
// Unambiguous Shift_JIS bytes (0x82 0xA0 = 'あ', invalid in UTF-8 and EUC-JP) remain lossless.
|
// Unambiguous Shift_JIS bytes (0x82 0xA0 = 'あ', invalid in UTF-8 and EUC-JP) remain lossless.
|
||||||
const unambiguousSjis = new Uint8Array([0x82, 0xa0]);
|
const unambiguousSjis = new Uint8Array([0x82, 0xa0]);
|
||||||
assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), { text: 'あ', lossless: true });
|
assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), {
|
||||||
|
text: '\uFEFFあ',
|
||||||
|
lossless: true,
|
||||||
|
});
|
||||||
|
|
||||||
const srt = formatSpansAsSrt([
|
const srt = formatSpansAsSrt([
|
||||||
{ start: 5.5, end: 7.0 },
|
{ start: 5.5, end: 7.0 },
|
||||||
@@ -180,3 +206,66 @@ test('decodeSubtitleBytesWithStatus marks lossless UTF-8 and lossy undecodable b
|
|||||||
assert.ok(srt.includes('00:00:01,250 --> 00:00:02,750'));
|
assert.ok(srt.includes('00:00:01,250 --> 00:00:02,750'));
|
||||||
assert.ok(srt.includes('00:00:05,500 --> 00:00:07,000'));
|
assert.ok(srt.includes('00:00:05,500 --> 00:00:07,000'));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('applyTimingToSubtitleFile writes a BOM only when the source had one or was not UTF-8', () => {
|
||||||
|
const srt = '1\n00:00:01,000 --> 00:00:02,000\nこんにちは\n';
|
||||||
|
const rewrite = (bytes: Uint8Array): string => {
|
||||||
|
const parsed = parseSubtitleFileContent(decodeSubtitleBytesWithStatus(bytes).text, 'a.srt');
|
||||||
|
return applyTimingToSubtitleFile(parsed, [0], [1], 1.0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const plain = rewrite(Buffer.from(srt, 'utf8'));
|
||||||
|
assert.ok(plain.startsWith('1\n00:00:02,000 --> 00:00:03,000'));
|
||||||
|
assert.ok(
|
||||||
|
rewrite(new Uint8Array([0xef, 0xbb, 0xbf, ...Buffer.from(srt, 'utf8')])).startsWith(
|
||||||
|
'\uFEFF1\n',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
// 'あ' in Shift_JIS (invalid UTF-8) is rewritten as UTF-8 with a BOM.
|
||||||
|
const sjis = new Uint8Array([
|
||||||
|
...Buffer.from('1\n00:00:01,000 --> 00:00:02,000\n', 'ascii'),
|
||||||
|
0x82,
|
||||||
|
0xa0,
|
||||||
|
]);
|
||||||
|
assert.ok(rewrite(sjis).startsWith('\uFEFF1\n00:00:02,000'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('signs and songs follow the dialogue line nearest in time, not in file order', () => {
|
||||||
|
const ass = [
|
||||||
|
'[Events]',
|
||||||
|
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
|
||||||
|
'Dialogue: 0,0:00:20.00,0:00:22.00,Default,,0,0,0,,一',
|
||||||
|
'Dialogue: 0,0:00:40.00,0:00:42.00,Default,,0,0,0,,二',
|
||||||
|
'Dialogue: 0,0:10:00.00,0:10:02.00,Default,,0,0,0,,三',
|
||||||
|
'Dialogue: 0,0:10:20.00,0:10:22.00,Default,,0,0,0,,四',
|
||||||
|
// Typesetting kept at the bottom of the file, timed near the first act.
|
||||||
|
'Dialogue: 0,0:00:10.00,0:00:12.00,OP Kara,,0,0,0,,{\\k20}ら',
|
||||||
|
'Dialogue: 0,0:01:30.00,0:01:32.00,Sign,,0,0,0,,看板',
|
||||||
|
].join('\n');
|
||||||
|
const parsed = parseSubtitleFileContent(ass, 'ep.ass');
|
||||||
|
const { dialogueIndices } = extractSpansFromParsedSubtitle(parsed);
|
||||||
|
assert.deepEqual(dialogueIndices, [0, 1, 2, 3]);
|
||||||
|
|
||||||
|
const rewritten = applyTimingToSubtitleFile(parsed, dialogueIndices, [0, 0, 5, 5], 1.0);
|
||||||
|
assert.ok(rewritten.includes('0:00:10.00,0:00:12.00,OP Kara'));
|
||||||
|
assert.ok(rewritten.includes('0:01:30.00,0:01:32.00,Sign'));
|
||||||
|
assert.ok(rewritten.includes('0:10:05.00,0:10:07.00,Default'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('only lines that open with a music mark count as lyrics', () => {
|
||||||
|
const srt = [
|
||||||
|
'1',
|
||||||
|
'00:00:01,000 --> 00:00:02,000',
|
||||||
|
'ありがとう♪',
|
||||||
|
'',
|
||||||
|
'2',
|
||||||
|
'00:00:03,000 --> 00:00:04,000',
|
||||||
|
'♪ 夢の中へ ♪',
|
||||||
|
'',
|
||||||
|
].join('\n');
|
||||||
|
const parsed = parseSubtitleFileContent(srt, 'a.srt');
|
||||||
|
assert.deepEqual(
|
||||||
|
parsed.events.map((event) => event.sign),
|
||||||
|
[false, true],
|
||||||
|
);
|
||||||
|
});
|
||||||
+106
-44
@@ -29,6 +29,11 @@ export interface ParsedSubtitleFile {
|
|||||||
events: ParsedSubtitleLine[];
|
events: ParsedSubtitleLine[];
|
||||||
/** False when byte decoding fell back to lossy replacement (e.g. U+FFFD). */
|
/** False when byte decoding fell back to lossy replacement (e.g. U+FFFD). */
|
||||||
lossless?: boolean;
|
lossless?: boolean;
|
||||||
|
/**
|
||||||
|
* True when the decoded text started with a U+FEFF marker: the source had a BOM or was
|
||||||
|
* not UTF-8. Rewrites keep a UTF-8 BOM so ANSI-codepage readers (VSFilter) do not misread.
|
||||||
|
*/
|
||||||
|
bom?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SIGN_STYLE_WORDS = new Set([
|
const SIGN_STYLE_WORDS = new Set([
|
||||||
@@ -51,26 +56,30 @@ const SIGN_STYLE_WORDS = new Set([
|
|||||||
'kara',
|
'kara',
|
||||||
'kfx',
|
'kfx',
|
||||||
'fx',
|
'fx',
|
||||||
'op',
|
|
||||||
'ed',
|
|
||||||
'opening',
|
'opening',
|
||||||
'ending',
|
'ending',
|
||||||
'note',
|
'note',
|
||||||
'notes',
|
'notes',
|
||||||
'tl',
|
|
||||||
'tn',
|
'tn',
|
||||||
'credit',
|
'credit',
|
||||||
'credits',
|
'credits',
|
||||||
'eyecatch',
|
'eyecatch',
|
||||||
'next',
|
'next',
|
||||||
'preview',
|
'preview',
|
||||||
'caption',
|
|
||||||
'banner',
|
'banner',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
// Only all-caps "OP"/"ED" mark song styles; "Ed" or "Op" are usually character names.
|
||||||
|
const UPPERCASE_ONLY_SIGN_STYLE_WORDS = new Set(['OP', 'ED']);
|
||||||
|
const JAPANESE_SIGN_STYLE_PATTERN = /看板|歌|タイトル/;
|
||||||
|
|
||||||
const TRACK_SIGNS_OR_SONGS_PATTERN =
|
const TRACK_SIGNS_OR_SONGS_PATTERN =
|
||||||
/(?:^|[^\p{L}\p{N}])(?:signs?(?:\s*(?:&|and|\+|\/|-|_)\s*songs?)?|songs?|lyrics?|karaoke|forced|s[\s&+_-]*s|op|ed|opening|ending)(?=$|[^\p{L}\p{N}])|看板|歌詞/iu;
|
/(?:^|[^\p{L}\p{N}])(?:signs?(?:\s*(?:&|and|\+|\/|-|_)\s*songs?)?|songs?|lyrics?|karaoke|forced|s[\s&+_-]*s|op|ed|opening|ending)(?=$|[^\p{L}\p{N}])|看板|歌詞/iu;
|
||||||
|
|
||||||
|
// "English (Full + Songs)" or "日本語 (歌詞あり)" are full dialogue tracks that also carry lyrics.
|
||||||
|
const TRACK_FULL_DIALOGUE_PATTERN =
|
||||||
|
/\b(?:full|dialogue|dialog|complete)\b|歌詞(?:あり|付き)|台詞|セリフ/i;
|
||||||
|
|
||||||
const SRT_VTT_TIMING_LINE_PATTERN =
|
const SRT_VTT_TIMING_LINE_PATTERN =
|
||||||
/^(\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(\s*-->\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(.*)$/;
|
/^(\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(\s*-->\s*)(\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}|\d{1,2}:\d{2}[,.]\d{1,3})(.*)$/;
|
||||||
|
|
||||||
@@ -90,56 +99,72 @@ function tryDecode(bytes: Uint8Array, encoding: string, fatal: boolean): string
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface DecodedSubtitleBytes {
|
export interface DecodedSubtitleBytes {
|
||||||
|
/**
|
||||||
|
* Decoded text. Starts with U+FEFF when the source had a BOM or was a non-UTF-8 encoding,
|
||||||
|
* so `parseSubtitleFileContent` records that a rewrite (always UTF-8) needs a BOM.
|
||||||
|
*/
|
||||||
text: string;
|
text: string;
|
||||||
lossless: boolean;
|
lossless: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BOM = '\uFEFF';
|
||||||
|
|
||||||
export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitleBytes {
|
export function decodeSubtitleBytesWithStatus(bytes: Uint8Array): DecodedSubtitleBytes {
|
||||||
|
const decoded = decodeSubtitleBytesRaw(bytes);
|
||||||
|
if (!decoded.lossless || !decoded.needsBom) {
|
||||||
|
return { text: decoded.text, lossless: decoded.lossless };
|
||||||
|
}
|
||||||
|
return { text: `${BOM}${decoded.text}`, lossless: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeSubtitleBytesRaw(bytes: Uint8Array): DecodedSubtitleBytes & { needsBom: boolean } {
|
||||||
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
|
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
|
||||||
const rest = bytes.subarray(3);
|
const rest = bytes.subarray(3);
|
||||||
const strict = tryDecode(rest, 'utf-8', true);
|
const strict = tryDecode(rest, 'utf-8', true);
|
||||||
if (strict !== null) return { text: strict, lossless: true };
|
if (strict !== null) return { text: strict, lossless: true, needsBom: true };
|
||||||
return { text: new TextDecoder('utf-8').decode(rest), lossless: false };
|
return { text: new TextDecoder('utf-8').decode(rest), lossless: false, needsBom: true };
|
||||||
}
|
}
|
||||||
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
|
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) {
|
||||||
const strict = tryDecode(bytes, 'utf-16le', true);
|
const strict = tryDecode(bytes, 'utf-16le', true);
|
||||||
if (strict !== null) return { text: strict, lossless: true };
|
if (strict !== null) return { text: strict, lossless: true, needsBom: true };
|
||||||
return {
|
return {
|
||||||
text: tryDecode(bytes, 'utf-16le', false) ?? new TextDecoder('utf-8').decode(bytes),
|
text: tryDecode(bytes, 'utf-16le', false) ?? new TextDecoder('utf-8').decode(bytes),
|
||||||
lossless: false,
|
lossless: false,
|
||||||
|
needsBom: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
|
if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) {
|
||||||
const strict = tryDecode(bytes, 'utf-16be', true);
|
const strict = tryDecode(bytes, 'utf-16be', true);
|
||||||
if (strict !== null) return { text: strict, lossless: true };
|
if (strict !== null) return { text: strict, lossless: true, needsBom: true };
|
||||||
return {
|
return {
|
||||||
text: tryDecode(bytes, 'utf-16be', false) ?? new TextDecoder('utf-8').decode(bytes),
|
text: tryDecode(bytes, 'utf-16be', false) ?? new TextDecoder('utf-8').decode(bytes),
|
||||||
lossless: false,
|
lossless: false,
|
||||||
|
needsBom: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const strictUtf8 = tryDecode(bytes, 'utf-8', true);
|
const strictUtf8 = tryDecode(bytes, 'utf-8', true);
|
||||||
if (strictUtf8 !== null) {
|
if (strictUtf8 !== null) {
|
||||||
return { text: strictUtf8, lossless: true };
|
return { text: strictUtf8, lossless: true, needsBom: false };
|
||||||
}
|
}
|
||||||
const shiftJis = tryDecode(bytes, 'shift_jis', true);
|
const shiftJis = tryDecode(bytes, 'shift_jis', true);
|
||||||
const eucJp = tryDecode(bytes, 'euc-jp', true);
|
const eucJp = tryDecode(bytes, 'euc-jp', true);
|
||||||
if (shiftJis !== null && eucJp === null) {
|
if (shiftJis !== null && eucJp === null) {
|
||||||
return { text: shiftJis, lossless: true };
|
return { text: shiftJis, lossless: true, needsBom: true };
|
||||||
}
|
}
|
||||||
if (eucJp !== null && shiftJis === null) {
|
if (eucJp !== null && shiftJis === null) {
|
||||||
return { text: eucJp, lossless: true };
|
return { text: eucJp, lossless: true, needsBom: true };
|
||||||
}
|
}
|
||||||
if (shiftJis !== null && eucJp !== null) {
|
if (shiftJis !== null && eucJp !== null) {
|
||||||
if (shiftJis === eucJp) {
|
if (shiftJis === eucJp) {
|
||||||
return { text: shiftJis, lossless: true };
|
return { text: shiftJis, lossless: true, needsBom: true };
|
||||||
}
|
}
|
||||||
return { text: eucJp, lossless: false };
|
return { text: eucJp, lossless: false, needsBom: true };
|
||||||
}
|
}
|
||||||
return { text: new TextDecoder('utf-8').decode(bytes), lossless: false };
|
return { text: new TextDecoder('utf-8').decode(bytes), lossless: false, needsBom: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decodeSubtitleBytes(bytes: Uint8Array): string {
|
export function decodeSubtitleBytes(bytes: Uint8Array): string {
|
||||||
return decodeSubtitleBytesWithStatus(bytes).text;
|
return decodeSubtitleBytesRaw(bytes).text;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -148,6 +173,11 @@ export function decodeSubtitleBytes(bytes: Uint8Array): string {
|
|||||||
* dialogue styles like "Subtitle", "Notebook", or "Edward" do not.
|
* dialogue styles like "Subtitle", "Notebook", or "Edward" do not.
|
||||||
*/
|
*/
|
||||||
export function splitStyleWords(name: string): string[] {
|
export function splitStyleWords(name: string): string[] {
|
||||||
|
return splitStyleTokens(name).map((word) => word.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same split as `splitStyleWords`, keeping the original letter case. */
|
||||||
|
function splitStyleTokens(name: string): string[] {
|
||||||
const words: string[] = [];
|
const words: string[] = [];
|
||||||
let word = '';
|
let word = '';
|
||||||
for (let i = 0; i < name.length; i += 1) {
|
for (let i = 0; i < name.length; i += 1) {
|
||||||
@@ -178,7 +208,7 @@ export function splitStyleWords(name: string): string[] {
|
|||||||
word = '';
|
word = '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
word += ch.toLowerCase();
|
word += ch;
|
||||||
}
|
}
|
||||||
if (word) {
|
if (word) {
|
||||||
words.push(word);
|
words.push(word);
|
||||||
@@ -188,7 +218,11 @@ export function splitStyleWords(name: string): string[] {
|
|||||||
|
|
||||||
export function isSignStyleOrEffect(value: string): boolean {
|
export function isSignStyleOrEffect(value: string): boolean {
|
||||||
if (!value.trim()) return false;
|
if (!value.trim()) return false;
|
||||||
return splitStyleWords(value).some((word) => SIGN_STYLE_WORDS.has(word));
|
if (JAPANESE_SIGN_STYLE_PATTERN.test(value)) return true;
|
||||||
|
return splitStyleTokens(value).some(
|
||||||
|
(token) =>
|
||||||
|
SIGN_STYLE_WORDS.has(token.toLowerCase()) || UPPERCASE_ONLY_SIGN_STYLE_WORDS.has(token),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isSignsOrSongsTrackMeta(track: {
|
export function isSignsOrSongsTrackMeta(track: {
|
||||||
@@ -197,8 +231,11 @@ export function isSignsOrSongsTrackMeta(track: {
|
|||||||
'external-filename'?: string;
|
'external-filename'?: string;
|
||||||
}): boolean {
|
}): boolean {
|
||||||
if (track.forced === true) return true;
|
if (track.forced === true) return true;
|
||||||
const combined = `${track.title ?? ''} ${track['external-filename'] ? (track['external-filename'].split(/[\\/]/).pop() ?? '') : ''}`;
|
const filename = track['external-filename']?.split(/[\\/]/).pop() ?? '';
|
||||||
return TRACK_SIGNS_OR_SONGS_PATTERN.test(combined);
|
// Judge title and filename separately so a full-dialogue hint only overrides its own field.
|
||||||
|
return [track.title ?? '', filename].some(
|
||||||
|
(field) => TRACK_SIGNS_OR_SONGS_PATTERN.test(field) && !TRACK_FULL_DIALOGUE_PATTERN.test(field),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseSubtitleTimestamp(raw: string): number | null {
|
export function parseSubtitleTimestamp(raw: string): number | null {
|
||||||
@@ -236,7 +273,8 @@ function cleanCuePlainText(raw: string): string {
|
|||||||
|
|
||||||
function isMusicOrLyricText(plainText: string, rawText: string): boolean {
|
function isMusicOrLyricText(plainText: string, rawText: string): boolean {
|
||||||
if (!plainText) return true;
|
if (!plainText) return true;
|
||||||
if (/[♪♫]/u.test(plainText)) return true;
|
// Lyrics open with a music mark ("♪ 夢の中へ ♪"); a trailing one is just tone ("ありがとう♪").
|
||||||
|
if (/^[\s(([【~~]*[♪♫♩♬]/u.test(plainText)) return true;
|
||||||
if (MUSIC_ONLY_TEXT_PATTERN.test(plainText)) return true;
|
if (MUSIC_ONLY_TEXT_PATTERN.test(plainText)) return true;
|
||||||
if (ASS_KARAOKE_TAG_PATTERN.test(rawText)) return true;
|
if (ASS_KARAOKE_TAG_PATTERN.test(rawText)) return true;
|
||||||
return false;
|
return false;
|
||||||
@@ -430,14 +468,16 @@ function parseSrtOrVttSubtitle(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function parseSubtitleFileContent(content: string, filename?: string): ParsedSubtitleFile {
|
export function parseSubtitleFileContent(content: string, filename?: string): ParsedSubtitleFile {
|
||||||
const cleanContent = content.startsWith('\uFEFF') ? content.slice(1) : content;
|
const bom = content.startsWith(BOM);
|
||||||
|
const cleanContent = bom ? content.slice(1) : content;
|
||||||
const eol: '\r\n' | '\n' = cleanContent.includes('\r\n') ? '\r\n' : '\n';
|
const eol: '\r\n' | '\n' = cleanContent.includes('\r\n') ? '\r\n' : '\n';
|
||||||
const rawLines = cleanContent.split(/\r?\n/);
|
const rawLines = cleanContent.split(/\r?\n/);
|
||||||
const format = detectFormat(cleanContent, filename);
|
const format = detectFormat(cleanContent, filename);
|
||||||
if (format === 'ass') {
|
const parsed =
|
||||||
return parseAssSubtitle(rawLines, eol);
|
format === 'ass'
|
||||||
}
|
? parseAssSubtitle(rawLines, eol)
|
||||||
return parseSrtOrVttSubtitle(rawLines, eol, format);
|
: parseSrtOrVttSubtitle(rawLines, eol, format);
|
||||||
|
return bom ? { ...parsed, bom } : parsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function extractSpansFromParsedSubtitle(
|
export function extractSpansFromParsedSubtitle(
|
||||||
@@ -507,28 +547,43 @@ export function formatVttTimestamp(seconds: number): string {
|
|||||||
return formatSrtTimestamp(seconds).replace(',', '.');
|
return formatSrtTimestamp(seconds).replace(',', '.');
|
||||||
}
|
}
|
||||||
|
|
||||||
function findNearestDialogueMoveIndex(
|
interface DialogueMoveAnchor {
|
||||||
eventIndex: number,
|
start: number;
|
||||||
dialogueIndices: readonly number[],
|
move: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dialogue (start, move) pairs sorted by start time, for time-based sign/song shifting. */
|
||||||
|
function buildDialogueMoveAnchors(
|
||||||
events: readonly ParsedSubtitleLine[],
|
events: readonly ParsedSubtitleLine[],
|
||||||
): number {
|
dialogueIndices: readonly number[],
|
||||||
if (dialogueIndices.length === 0) return 0;
|
movesSec: readonly number[],
|
||||||
|
): DialogueMoveAnchor[] {
|
||||||
|
return dialogueIndices
|
||||||
|
.map((eventIndex, k) => ({ start: events[eventIndex]!.start, move: movesSec[k] ?? 0 }))
|
||||||
|
.sort((a, b) => a.start - b.start);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shift of the dialogue line nearest `start` in time. ASS files often keep typesetting
|
||||||
|
* or OP/ED karaoke at the top or bottom of the file, so file position is meaningless.
|
||||||
|
*/
|
||||||
|
function nearestDialogueMove(anchors: readonly DialogueMoveAnchor[], start: number): number {
|
||||||
|
if (anchors.length === 0) return 0;
|
||||||
let lo = 0;
|
let lo = 0;
|
||||||
let hi = dialogueIndices.length;
|
let hi = anchors.length;
|
||||||
while (lo < hi) {
|
while (lo < hi) {
|
||||||
const mid = (lo + hi) >>> 1;
|
const mid = (lo + hi) >>> 1;
|
||||||
if (dialogueIndices[mid]! < eventIndex) {
|
if (anchors[mid]!.start < start) {
|
||||||
lo = mid + 1;
|
lo = mid + 1;
|
||||||
} else {
|
} else {
|
||||||
hi = mid;
|
hi = mid;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (lo === 0) return 0;
|
if (lo === 0) return anchors[0]!.move;
|
||||||
if (lo >= dialogueIndices.length) return dialogueIndices.length - 1;
|
if (lo >= anchors.length) return anchors[anchors.length - 1]!.move;
|
||||||
const eventStart = events[eventIndex]!.start;
|
const prev = anchors[lo - 1]!;
|
||||||
const prevStart = events[dialogueIndices[lo - 1]!]!.start;
|
const next = anchors[lo]!;
|
||||||
const nextStart = events[dialogueIndices[lo]!]!.start;
|
return start - prev.start <= next.start - start ? prev.move : next.move;
|
||||||
return Math.abs(eventStart - prevStart) <= Math.abs(nextStart - eventStart) ? lo - 1 : lo;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -543,7 +598,7 @@ export function applyTimingToSubtitleFile(
|
|||||||
ratio: number,
|
ratio: number,
|
||||||
): string {
|
): string {
|
||||||
if (parsed.events.length === 0 || dialogueIndices.length === 0 || movesSec.length === 0) {
|
if (parsed.events.length === 0 || dialogueIndices.length === 0 || movesSec.length === 0) {
|
||||||
return parsed.rawLines.join(parsed.eol);
|
return serializeSubtitleLines(parsed, parsed.rawLines);
|
||||||
}
|
}
|
||||||
|
|
||||||
const outLines = [...parsed.rawLines];
|
const outLines = [...parsed.rawLines];
|
||||||
@@ -551,14 +606,12 @@ export function applyTimingToSubtitleFile(
|
|||||||
for (let k = 0; k < dialogueIndices.length; k += 1) {
|
for (let k = 0; k < dialogueIndices.length; k += 1) {
|
||||||
dialogueMoveByEventIndex.set(dialogueIndices[k]!, movesSec[k] ?? 0);
|
dialogueMoveByEventIndex.set(dialogueIndices[k]!, movesSec[k] ?? 0);
|
||||||
}
|
}
|
||||||
|
const anchors = buildDialogueMoveAnchors(parsed.events, dialogueIndices, movesSec);
|
||||||
|
|
||||||
for (let i = 0; i < parsed.events.length; i += 1) {
|
for (let i = 0; i < parsed.events.length; i += 1) {
|
||||||
const ev = parsed.events[i]!;
|
const ev = parsed.events[i]!;
|
||||||
const directMove = dialogueMoveByEventIndex.get(i);
|
const directMove = dialogueMoveByEventIndex.get(i);
|
||||||
const shift =
|
const shift = directMove ?? nearestDialogueMove(anchors, ev.start);
|
||||||
directMove !== undefined
|
|
||||||
? directMove
|
|
||||||
: (movesSec[findNearestDialogueMoveIndex(i, dialogueIndices, parsed.events)] ?? 0);
|
|
||||||
|
|
||||||
const newStart = Math.max(0, ev.start * ratio + shift);
|
const newStart = Math.max(0, ev.start * ratio + shift);
|
||||||
const newEnd = Math.max(newStart + 0.05, ev.end * ratio + shift);
|
const newEnd = Math.max(newStart + 0.05, ev.end * ratio + shift);
|
||||||
@@ -589,7 +642,16 @@ export function applyTimingToSubtitleFile(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return outLines.join(parsed.eol);
|
return serializeSubtitleLines(parsed, outLines);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Join rewritten lines with the source line ending, restoring a BOM when the source needs one. */
|
||||||
|
export function serializeSubtitleLines(
|
||||||
|
parsed: Pick<ParsedSubtitleFile, 'eol' | 'bom'>,
|
||||||
|
lines: readonly string[],
|
||||||
|
): string {
|
||||||
|
const joined = lines.join(parsed.eol);
|
||||||
|
return parsed.bom ? `${BOM}${joined}` : joined;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -245,6 +245,14 @@ export function codecToExtension(codec: string | undefined): string | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ffmpeg has no TTML decoder, so TTML tracks can only come from servers that convert them
|
||||||
|
* (Jellyfin delivers them as SRT); local extraction would fail.
|
||||||
|
*/
|
||||||
|
export function canFfmpegExtractSubtitleExtension(extension: string): boolean {
|
||||||
|
return extension !== 'ttml';
|
||||||
|
}
|
||||||
|
|
||||||
export function extensionToFfmpegMuxer(extension: string): string {
|
export function extensionToFfmpegMuxer(extension: string): string {
|
||||||
if (extension === 'vtt') return 'webvtt';
|
if (extension === 'vtt') return 'webvtt';
|
||||||
return extension;
|
return extension;
|
||||||
|
|||||||
Reference in new issue
Block a user