diff --git a/src/subsync/audio-speech.test.ts b/src/subsync/audio-speech.test.ts index e5a51772..72241410 100644 --- a/src/subsync/audio-speech.test.ts +++ b/src/subsync/audio-speech.test.ts @@ -190,3 +190,54 @@ test('cacheEmbeddedSubtitleTrack populates single-pass cache, ignores empty pars 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 }); + } +}); diff --git a/src/subsync/audio-speech.ts b/src/subsync/audio-speech.ts index f95e153b..73753b8a 100644 --- a/src/subsync/audio-speech.ts +++ b/src/subsync/audio-speech.ts @@ -9,7 +9,13 @@ import { type ParsedSubtitleFile, type SubtitleTimeSpan, } 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_FILTER = 'highpass=f=200,lowpass=f=3400'; @@ -135,6 +141,14 @@ export function getCachedEmbeddedSubtitles( 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( videoPath: string, ffIndex: number, @@ -378,7 +392,7 @@ function streamFfmpegPcm( chunks.push(chunk); }); child.stderr.on('data', (chunk: Buffer) => { - stderr += chunk.toString(); + stderr = appendStderrTail(stderr, chunk); }); child.on('error', (error: Error) => { finishError(error); @@ -564,7 +578,7 @@ function spawnFfmpegWithStdout( chunks.push(chunk); }); child.stderr.on('data', (chunk: Buffer) => { - stderr += chunk.toString(); + stderr = appendStderrTail(stderr, chunk); }); child.on('error', (error: Error) => { finishError(error); @@ -704,7 +718,10 @@ export async function extractSinglePassRipMedia( new Map(); 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; if (missingTracks.length === 0 && !needAudio) { @@ -793,18 +810,22 @@ export async function extractSinglePassRipMedia( ); const updatedSubs = new Map(cachedSubs); + let cacheChanged = false; for (const { ffIndex, outPath } of trackOutputs) { if (!fileExists(outPath)) continue; try { const bytes = fs.readFileSync(outPath); const parsed = parseSubtitleFileContent(decodeSubtitleBytes(bytes), outPath); updatedSubs.set(ffIndex, parsed); + // Like cacheEmbeddedSubtitleTrack: empty results are returned but never cached. + if (parsed.events.length > 0) cacheChanged = true; } catch { // Ignore individual unparseable track. } } - if (updatedSubs.size > 0) { - rememberLru(embeddedSubtitlesCache, fileKey, updatedSubs); + if (cacheChanged) { + const cacheable = new Map([...updatedSubs].filter(([, parsed]) => parsed.events.length > 0)); + rememberLru(embeddedSubtitlesCache, fileKey, cacheable); } let audioSpeech: AudioSpeechResult | null = options.includeAudio ? cachedAudio : null; diff --git a/src/subsync/subtitle-lines.test.ts b/src/subsync/subtitle-lines.test.ts index f7439465..9e185611 100644 --- a/src/subsync/subtitle-lines.test.ts +++ b/src/subsync/subtitle-lines.test.ts @@ -20,6 +20,10 @@ test('isSignStyleOrEffect separates signs/songs styles from dialogue styles', () 'Main Top', 'DefaultItalics', 'Edward', + 'Ed', + 'Op', + 'TL', + 'Caption', ]) { assert.equal(isSignStyleOrEffect(dialogueStyle), false, `${dialogueStyle} should be dialogue`); } @@ -38,6 +42,10 @@ test('isSignStyleOrEffect separates signs/songs styles from dialogue styles', () 'Insert Song', 'Lyrics', 'Typeset', + 'ED', + '看板', + 'OP歌詞', + 'タイトル', ]) { 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({ title: 'English [Full Dialogue]' }), 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', () => { @@ -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', () => { const bomBytes = new Uint8Array([0xef, 0xbb, 0xbf, ...Buffer.from('hello', 'utf8')]); 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. 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. const unambiguousSjis = new Uint8Array([0x82, 0xa0]); - assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), { text: 'あ', lossless: true }); + assert.deepEqual(decodeSubtitleBytesWithStatus(unambiguousSjis), { + text: '\uFEFFあ', + lossless: true, + }); const srt = formatSpansAsSrt([ { 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: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], + ); +}); diff --git a/src/subsync/subtitle-lines.ts b/src/subsync/subtitle-lines.ts index e8f09078..89e6670e 100644 --- a/src/subsync/subtitle-lines.ts +++ b/src/subsync/subtitle-lines.ts @@ -29,6 +29,11 @@ export interface ParsedSubtitleFile { events: ParsedSubtitleLine[]; /** False when byte decoding fell back to lossy replacement (e.g. U+FFFD). */ 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([ @@ -51,26 +56,30 @@ const SIGN_STYLE_WORDS = new Set([ 'kara', 'kfx', 'fx', - 'op', - 'ed', 'opening', 'ending', 'note', 'notes', - 'tl', 'tn', 'credit', 'credits', 'eyecatch', 'next', 'preview', - 'caption', '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 = /(?:^|[^\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 = /^(\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 { + /** + * 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; lossless: boolean; } +const BOM = '\uFEFF'; + 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) { const rest = bytes.subarray(3); const strict = tryDecode(rest, 'utf-8', true); - if (strict !== null) return { text: strict, lossless: true }; - return { text: new TextDecoder('utf-8').decode(rest), lossless: false }; + if (strict !== null) return { text: strict, lossless: true, needsBom: true }; + return { text: new TextDecoder('utf-8').decode(rest), lossless: false, needsBom: true }; } if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xfe) { 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 { text: tryDecode(bytes, 'utf-16le', false) ?? new TextDecoder('utf-8').decode(bytes), lossless: false, + needsBom: true, }; } if (bytes.length >= 2 && bytes[0] === 0xfe && bytes[1] === 0xff) { 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 { text: tryDecode(bytes, 'utf-16be', false) ?? new TextDecoder('utf-8').decode(bytes), lossless: false, + needsBom: true, }; } const strictUtf8 = tryDecode(bytes, 'utf-8', true); if (strictUtf8 !== null) { - return { text: strictUtf8, lossless: true }; + return { text: strictUtf8, lossless: true, needsBom: false }; } const shiftJis = tryDecode(bytes, 'shift_jis', true); const eucJp = tryDecode(bytes, 'euc-jp', true); if (shiftJis !== null && eucJp === null) { - return { text: shiftJis, lossless: true }; + return { text: shiftJis, lossless: true, needsBom: true }; } if (eucJp !== null && shiftJis === null) { - return { text: eucJp, lossless: true }; + return { text: eucJp, lossless: true, needsBom: true }; } if (shiftJis !== null && eucJp !== null) { 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 { - 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. */ 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[] = []; let word = ''; for (let i = 0; i < name.length; i += 1) { @@ -178,7 +208,7 @@ export function splitStyleWords(name: string): string[] { word = ''; } } - word += ch.toLowerCase(); + word += ch; } if (word) { words.push(word); @@ -188,7 +218,11 @@ export function splitStyleWords(name: string): string[] { export function isSignStyleOrEffect(value: string): boolean { 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: { @@ -197,8 +231,11 @@ export function isSignsOrSongsTrackMeta(track: { 'external-filename'?: string; }): boolean { if (track.forced === true) return true; - const combined = `${track.title ?? ''} ${track['external-filename'] ? (track['external-filename'].split(/[\\/]/).pop() ?? '') : ''}`; - return TRACK_SIGNS_OR_SONGS_PATTERN.test(combined); + const filename = track['external-filename']?.split(/[\\/]/).pop() ?? ''; + // 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 { @@ -236,7 +273,8 @@ function cleanCuePlainText(raw: string): string { function isMusicOrLyricText(plainText: string, rawText: string): boolean { 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 (ASS_KARAOKE_TAG_PATTERN.test(rawText)) return true; return false; @@ -430,14 +468,16 @@ function parseSrtOrVttSubtitle( } 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 rawLines = cleanContent.split(/\r?\n/); const format = detectFormat(cleanContent, filename); - if (format === 'ass') { - return parseAssSubtitle(rawLines, eol); - } - return parseSrtOrVttSubtitle(rawLines, eol, format); + const parsed = + format === 'ass' + ? parseAssSubtitle(rawLines, eol) + : parseSrtOrVttSubtitle(rawLines, eol, format); + return bom ? { ...parsed, bom } : parsed; } export function extractSpansFromParsedSubtitle( @@ -507,28 +547,43 @@ export function formatVttTimestamp(seconds: number): string { return formatSrtTimestamp(seconds).replace(',', '.'); } -function findNearestDialogueMoveIndex( - eventIndex: number, - dialogueIndices: readonly number[], +interface DialogueMoveAnchor { + start: number; + move: number; +} + +/** Dialogue (start, move) pairs sorted by start time, for time-based sign/song shifting. */ +function buildDialogueMoveAnchors( events: readonly ParsedSubtitleLine[], -): number { - if (dialogueIndices.length === 0) return 0; + dialogueIndices: readonly number[], + 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 hi = dialogueIndices.length; + let hi = anchors.length; while (lo < hi) { const mid = (lo + hi) >>> 1; - if (dialogueIndices[mid]! < eventIndex) { + if (anchors[mid]!.start < start) { lo = mid + 1; } else { hi = mid; } } - if (lo === 0) return 0; - if (lo >= dialogueIndices.length) return dialogueIndices.length - 1; - const eventStart = events[eventIndex]!.start; - const prevStart = events[dialogueIndices[lo - 1]!]!.start; - const nextStart = events[dialogueIndices[lo]!]!.start; - return Math.abs(eventStart - prevStart) <= Math.abs(nextStart - eventStart) ? lo - 1 : lo; + if (lo === 0) return anchors[0]!.move; + if (lo >= anchors.length) return anchors[anchors.length - 1]!.move; + const prev = anchors[lo - 1]!; + const next = anchors[lo]!; + return start - prev.start <= next.start - start ? prev.move : next.move; } /** @@ -543,7 +598,7 @@ export function applyTimingToSubtitleFile( ratio: number, ): string { 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]; @@ -551,14 +606,12 @@ export function applyTimingToSubtitleFile( for (let k = 0; k < dialogueIndices.length; k += 1) { dialogueMoveByEventIndex.set(dialogueIndices[k]!, movesSec[k] ?? 0); } + const anchors = buildDialogueMoveAnchors(parsed.events, dialogueIndices, movesSec); for (let i = 0; i < parsed.events.length; i += 1) { const ev = parsed.events[i]!; const directMove = dialogueMoveByEventIndex.get(i); - const shift = - directMove !== undefined - ? directMove - : (movesSec[findNearestDialogueMoveIndex(i, dialogueIndices, parsed.events)] ?? 0); + const shift = directMove ?? nearestDialogueMove(anchors, ev.start); const newStart = Math.max(0, ev.start * 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, + lines: readonly string[], +): string { + const joined = lines.join(parsed.eol); + return parsed.bom ? `${BOM}${joined}` : joined; } /** diff --git a/src/subsync/utils.ts b/src/subsync/utils.ts index 2842d6a0..5bac372c 100644 --- a/src/subsync/utils.ts +++ b/src/subsync/utils.ts @@ -245,6 +245,14 @@ export function codecToExtension(codec: string | undefined): string | 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 { if (extension === 'vtt') return 'webvtt'; return extension;