diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 312ae5c7..19200fcf 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -35,7 +35,7 @@ Update checks and startup launcher migration share a serialized update-state sto - `src/core/services/subtitle-generation*.ts` shares local whisper.cpp transcription, safe model downloads, and progress between the launcher and Electron. Optional dialogue mode retains both Silero-detected speech and other audible sections, omits confidently silent gaps, decodes passages independently, and restores original media timing. `src/main/runtime/subtitle-generation-runtime.ts` owns the overlay job lifecycle and only loads completed subtitles into the same media. For Jellyfin playback it reads the item's original-file stream (`toJellyfinOriginalStreamUrl`) into one reused output folder, where each run best-effort deletes earlier files and writes a uniquely named SRT; transcoded playback uses Jellyfin's audio index and only external references, since mpv's track indexes describe the transcode. Subprocess errors redact URL tokens; `src/shared/subtitle-generation*.ts` owns configuration, the multilingual model catalog, and IPC contracts. The overlay runtime retains a session model selection, validates picker requests through IPC, and keeps external model paths authoritative. - Subtitle model recommendations use bounded `nvidia-smi` and Whisper CUDA discovery probes in `subtitle-generation-acceleration.ts`. The overlay runtime caches results by executable path for 30 seconds and exposes acceleration status through the existing status IPC. Recommendations do not alter model selection or transcription arguments. - `subtitle-generation-reference.ts` ranks mpv's loaded text subtitle tracks, excludes signs/songs and forced references, and extracts timing hints with FFmpeg. The overlay and launcher snapshot references only for matching media, including active subtitle delays. Hints guide long-passage cuts with or without VAD; they never limit audio coverage or replace Whisper timestamps. -- `src/subsync/` and `src/core/services/subsync*.ts` own built-in subtitle synchronization: format-preserving SRT/VTT/ASS parsing and sign/song/karaoke stripping (`subtitle-lines.ts`), pure-TypeScript alass-based single-shift, framerate-ratio, Viterbi piecewise, and broadcast multi-piece alignment with statistical standing/start-agreement scoring (`alass-align.ts`), cached local audio speech detection preferring Silero VAD when available with a built-in ffmpeg voice-band PCM VAD fallback, single-pass multi-track `ffmpeg` demuxing for embedded tracks, and fast parallel seeked-window audio verification for external-only references (`audio-speech.ts`), plus sidecar/track candidate discovery and audio-alignment verification (`reference-discovery.ts`). Triggering subsync in default `auto` mode evaluates all available tracks and sidecars (skipping signs/songs-tagged embedded tracks), verifies references against audio on local media so misaligned secondary tracks are skipped in favor of better-aligned tracks or audio speech, applies confident syncs automatically, and opens the guided modal (supporting built-in, external `alass`/`ffsubsync`, file browse, sign/split toggles, and manual offset) whenever automatic sync cannot finish cleanly. The service is split into `subsync.ts` (entry points) over `subsync-context`, `subsync-files`, `subsync-candidates`, `subsync-manual`, `subsync-auto`, and `subsync-shared`. Alignment and candidate scoring run in a reusable worker thread (`src/subsync/align-worker.ts`, falling back to the main thread if the worker cannot start), so long movies do not stall mpv IPC or the overlay. Every run goes through `runWithMediaChangeAbort`: when mpv's `path` changes it aborts the run's signal, which kills spawned ffmpeg/VAD/alass/ffsubsync (process tree on Windows) and terminates the align worker, so the global subsync lock is released immediately. In-place rewrites keep a one-time `.orig` backup. +- `src/subsync/` and `src/core/services/subsync*.ts` own built-in subtitle synchronization: format-preserving SRT/VTT/ASS parsing and sign/song/karaoke stripping (`subtitle-lines.ts`), pure-TypeScript alass-based single-shift, framerate-ratio, Viterbi piecewise, and broadcast multi-piece alignment with statistical standing/start-agreement scoring (`alass-align.ts`), cached local audio speech detection preferring Silero VAD when available with a built-in ffmpeg voice-band PCM VAD fallback, single-pass multi-track `ffmpeg` demuxing for embedded tracks, and fast parallel seeked-window audio verification for external-only references (`audio-speech.ts`), plus sidecar/track candidate discovery and audio-alignment verification (`reference-discovery.ts`). Triggering subsync in default `auto` mode evaluates all available tracks and sidecars (skipping signs/songs-tagged embedded tracks), verifies references against audio on local media so misaligned secondary tracks are skipped in favor of better-aligned tracks or audio speech, applies confident syncs automatically, and opens the guided modal (supporting built-in, external `alass`/`ffsubsync`, file browse, sign/split toggles, and manual offset) whenever automatic sync cannot finish cleanly. The service is split into `subsync.ts` (entry points) over `subsync-context`, `subsync-files`, `subsync-candidates`, `subsync-manual`, `subsync-auto`, and `subsync-shared`. Alignment and candidate scoring run in a reusable worker thread (`src/subsync/align-worker.ts`, falling back to the main thread if the worker cannot start), so long movies do not stall mpv IPC or the overlay. Every run goes through `runWithMediaChangeAbort`: when mpv's `path` changes it aborts the run's signal, which kills spawned ffmpeg/VAD/alass/ffsubsync (process tree on Windows) and terminates the align worker, so the global subsync lock is released immediately. In-place rewrites keep a one-time `.orig` backup. A retimed embedded or remote track lives in a `subminer-subsync-*` temp dir that is kept while mpv lists the file, pruned at the start of the next run once it does not, and removed on exit; dirs older than a day from crashed sessions are swept once per process. - `src/main/runtime/subtitle-selection.ts` reads and validates mpv subtitle tracks and applies primary/secondary selections. Its opt-in session shortcut opens the shared overlay modal window, with renderer focus and subtitle suppression handled by the modal registry. - `src/shared/session-key-sequences.ts` rejects sequence prefixes reserved by single-key actions. The session-binding compiler reserves configured and built-in overlay keys; `src/main/runtime/session-bindings-runtime.ts` adds active mpv bindings and publishes the effective list to both the plugin artifact and the renderer through `session-bindings:changed`. mpv no-op `ignore` bindings do not reserve prefixes. - `src/core/services/plugins/` owns user plugins: discovery from `/plugins//plugin.json` for ids enabled in `plugins`, the per-plugin `ctx`, guarded callbacks, and `exec` (no shell, AppImage `LD_LIBRARY_PATH` dropped). `src/main/assemblies/plugins.ts` builds the host. The playback assembly attaches each new mpv client so plugin listeners survive client replacement, the startup assembly starts plugins from the app-ready path after logging is configured, and the `will-quit` cleanup unloads them first, before any teardown. Plugins run in the main process with no sandbox. `src/plugin-api.ts` is the standalone public v1 type contract; internal mpv event and session-action types derive from it. Manifests may declare `apiVersion`, which is checked before loading code. Async activation is bounded and actions wait only for their own plugin. The host owns cached media snapshots and playback ids, including repeated loads of the same path. `ctx.signal` aborts as unloading starts; `ctx.onDispose` manages outside resources and late registrations are disposed immediately. Awaitable `ctx.mpv.request` uses the existing request/response transport. Plugin actions are the `runPluginAction` session action (keybinding command `__plugin-action:/`, CLI `--plugin-action /`); `runAction` waits for an in-progress load so a cold-start CLI action is not dropped. Each plugin gets `/plugin-data//` as `ctx.dataDir`. `ctx.anki` carries the `card-mined` event with unique kept `noteIds` and per-original-note records. Sentence-card creation snapshots media and subtitle context before asynchronous work; the proxy snapshots before forwarding an upstream request. `AnkiIntegration` keeps provenance under original ids through merges and queued YouTube jobs; polling uses null provenance. The event is fed by `AnkiIntegration.setCardsReadyCallback`: polling, the AnkiConnect proxy, and sentence-card creation report a note once its enrichment finishes (or when they see it, if auto-update is off); `AnkiIntegration` holds a sentence card's report until field grouping finishes, and the pending YouTube media queue reports notes whose media it is still waiting on (directly or through the note field grouping merged them into), which is later than `recordCardsMined` (stats counts at add time). Stats-dashboard mining does not emit it. `ctx.anki.invoke` sends one action to the effective `ankiConnect.url` with no retries. `src/main/runtime/plugin-window-runtime.ts` owns plugin windows (`ctx.ui.openWindow`): one window per plugin + HTML path, raised above the overlay like the settings windows, destroyed on unload. `src/main/runtime/plugin-panel-runtime.ts` owns the single `plugin-panel` modal: a new panel aborts the previous handle's signal, updates broadcast to both overlay windows keyed by `panelId`, and the latest content is re-sent once the renderer acknowledges the open. diff --git a/scripts/test-lanes.ts b/scripts/test-lanes.ts index f6310ef4..3d41621e 100644 --- a/scripts/test-lanes.ts +++ b/scripts/test-lanes.ts @@ -34,7 +34,11 @@ export const testLanes: Record = { subtitle: { roots: ['src/subsync'], include: ['.test.ts'], - extraFiles: ['src/core/services/subsync.test.ts', 'src/renderer/modals/subsync.test.ts'], + extraFiles: [ + 'src/core/services/subsync.test.ts', + 'src/core/services/subsync-files.test.ts', + 'src/renderer/modals/subsync.test.ts', + ], }, scripts: { roots: ['scripts'], diff --git a/src/core/services/subsync-auto.ts b/src/core/services/subsync-auto.ts index 159d7ade..43fb6761 100644 --- a/src/core/services/subsync-auto.ts +++ b/src/core/services/subsync-auto.ts @@ -84,7 +84,6 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis const targetSlot = resolveTargetSlot(targetTrack, context); let targetExtraction: FileExtractionResult | null = null; - let keepTempTarget = false; try { try { targetExtraction = await extractSubtitleTrackToFile( @@ -184,9 +183,6 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis return; } writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget); - if (targetExtraction!.temporary) { - keepTempTarget = true; - } await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack); deps.showMpvOsd(formatAlignmentSummary(sourceLabel, alignment)); }; @@ -495,8 +491,6 @@ export async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promis deps.openManualPicker(payload); deps.showMpvOsd('Subsync needs guidance: opened options'); } finally { - if (!keepTempTarget) { - cleanupTemporaryFile(targetExtraction); - } + cleanupTemporaryFile(targetExtraction); } } diff --git a/src/core/services/subsync-files.test.ts b/src/core/services/subsync-files.test.ts new file mode 100644 index 00000000..5f3df881 --- /dev/null +++ b/src/core/services/subsync-files.test.ts @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { cleanupTemporaryFile, pruneRetainedSubsyncTempDirs } from './subsync-files'; + +test('synced embedded-track temp dirs keep only the loaded file and go away once mpv drops it', () => { + const isolatedTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-files-test-')); + const previousTmpDir = process.env.TMPDIR; + process.env.TMPDIR = isolatedTmp; + try { + // Left behind by a crashed session two days ago. + const staleDir = fs.mkdtempSync(path.join(isolatedTmp, 'subminer-subsync-')); + const twoDaysAgo = (Date.now() - 2 * 24 * 60 * 60 * 1000) / 1000; + fs.utimesSync(staleDir, twoDaysAgo, twoDaysAgo); + + // Extraction of an embedded target plus the retimed copy mpv loaded. + const runDir = fs.mkdtempSync(path.join(isolatedTmp, 'subminer-subsync-')); + const extractedPath = path.join(runDir, 'track_2.ass'); + const retimedPath = path.join(runDir, 'track_2_retimed.ass'); + fs.writeFileSync(extractedPath, 'original'); + fs.writeFileSync(retimedPath, 'retimed'); + + cleanupTemporaryFile({ path: extractedPath, temporary: true }); + assert.deepEqual(fs.readdirSync(runDir), ['track_2_retimed.ass']); + + pruneRetainedSubsyncTempDirs([retimedPath]); + assert.equal(fs.existsSync(runDir), true, 'mpv still lists the retimed file'); + assert.equal(fs.existsSync(staleDir), false, 'stale dirs from old sessions are swept'); + + pruneRetainedSubsyncTempDirs(['/media/ep02.ja.srt']); + assert.equal(fs.existsSync(runDir), false, 'dropped once mpv no longer lists it'); + } finally { + if (previousTmpDir === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previousTmpDir; + fs.rmSync(isolatedTmp, { recursive: true, force: true }); + } +}); + +test('cleanupTemporaryFile removes a reference extraction and its dir entirely', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-subsync-')); + const extractedPath = path.join(dir, 'track_3.srt'); + fs.writeFileSync(extractedPath, 'reference'); + + cleanupTemporaryFile({ path: extractedPath, temporary: true }); + assert.equal(fs.existsSync(dir), false); +}); diff --git a/src/core/services/subsync-files.ts b/src/core/services/subsync-files.ts index af7faf18..960fd678 100644 --- a/src/core/services/subsync-files.ts +++ b/src/core/services/subsync-files.ts @@ -155,19 +155,86 @@ export async function extractSubtitleTrackToFile( } } +const SUBSYNC_TEMP_DIR_PREFIX = 'subminer-subsync-'; +const STALE_SUBSYNC_TEMP_DIR_MS = 24 * 60 * 60 * 1000; + +/** + * Temp dirs still holding a retimed subtitle that mpv loaded (embedded or remote target). + * Pruned by `pruneRetainedSubsyncTempDirs` once mpv no longer lists the file, and on exit. + */ +const retainedSubsyncTempDirs = new Set(); +let exitCleanupRegistered = false; +let staleSweepDone = false; + +function removeDirQuietly(dir: string): void { + try { + fs.rmSync(dir, { recursive: true, force: true }); + } catch { + // Best-effort temp cleanup. + } +} + +function retainSubsyncTempDir(dir: string): void { + retainedSubsyncTempDirs.add(dir); + if (exitCleanupRegistered) return; + exitCleanupRegistered = true; + process.once('exit', () => { + for (const retained of retainedSubsyncTempDirs) removeDirQuietly(retained); + }); +} + +/** + * Remove a temporary extraction and its mkdtemp dir. A dir that still holds the retimed + * subtitle mpv loaded stays on disk (mpv and the subtitle sidebar read it) and is retained. + */ export function cleanupTemporaryFile(extraction: FileExtractionResult | null): void { if (!extraction || !extraction.temporary) return; + removeIfExists(extraction.path); + const dir = path.dirname(extraction.path); try { - if (fileExists(extraction.path)) { - fs.unlinkSync(extraction.path); - } - } catch {} + fs.rmdirSync(dir); + } catch { + if (fs.existsSync(dir)) retainSubsyncTempDir(dir); + } +} + +/** + * Drop retained temp dirs whose files mpv no longer lists (`referencedPaths` are the current + * external subtitle filenames), and once per process sweep subsync temp dirs a crashed + * session left behind more than a day ago. + */ +export function pruneRetainedSubsyncTempDirs( + referencedPaths: readonly string[], + now: number = Date.now(), +): void { + for (const dir of retainedSubsyncTempDirs) { + const prefix = `${dir}${path.sep}`; + if (referencedPaths.some((filePath) => filePath.startsWith(prefix))) continue; + removeDirQuietly(dir); + retainedSubsyncTempDirs.delete(dir); + } + if (staleSweepDone) return; + staleSweepDone = true; + const tmpRoot = os.tmpdir(); + let entries: string[] = []; try { - const dir = path.dirname(extraction.path); - if (fs.existsSync(dir)) { - fs.rmdirSync(dir); + entries = fs.readdirSync(tmpRoot); + } catch { + return; + } + for (const name of entries) { + if (!name.startsWith(SUBSYNC_TEMP_DIR_PREFIX)) continue; + const dir = path.join(tmpRoot, name); + if (retainedSubsyncTempDirs.has(dir)) continue; + try { + const stat = fs.statSync(dir); + if (stat.isDirectory() && now - stat.mtimeMs > STALE_SUBSYNC_TEMP_DIR_MS) { + removeDirQuietly(dir); + } + } catch { + // Raced with another cleanup; ignore. } - } catch {} + } } const MAX_REFERENCE_FILE_BYTES = 20 * 1024 * 1024; diff --git a/src/core/services/subsync-manual.ts b/src/core/services/subsync-manual.ts index 5882f724..8e99ec73 100644 --- a/src/core/services/subsync-manual.ts +++ b/src/core/services/subsync-manual.ts @@ -87,7 +87,6 @@ async function runBuiltinSubsync( const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); let refExtraction: FileExtractionResult | null = null; - let keepTempTarget = false; try { const parsedTarget = readAndParseSubtitleFile(targetExtraction.path); if (parsedTarget.events.length === 0) { @@ -183,9 +182,6 @@ async function runBuiltinSubsync( } writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget); - if (targetExtraction.temporary) { - keepTempTarget = true; - } await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack); return { ok: true, @@ -193,9 +189,7 @@ async function runBuiltinSubsync( }; } finally { cleanupTemporaryFile(refExtraction); - if (!keepTempTarget) { - cleanupTemporaryFile(targetExtraction); - } + cleanupTemporaryFile(targetExtraction); } } @@ -217,8 +211,6 @@ async function runManualOffsetSubsync( ); const replaceTarget = resolved.replace !== false && !targetExtraction.temporary; const outputPath = buildRetimedPath(targetExtraction.path, replaceTarget); - - let keepTempTarget = false; try { const parsedTarget = readAndParseSubtitleFile(targetExtraction.path); if (parsedTarget.events.length === 0) { @@ -234,18 +226,13 @@ async function runManualOffsetSubsync( return { ok: false, message: PLAYBACK_CHANGED_RESULT_MESSAGE }; } writeRetimedContent(outputPath, rewritten, replaceTarget); - if (targetExtraction.temporary) { - keepTempTarget = true; - } await loadSyncedSubtitle(client, outputPath, targetSlot, targetTrack); return { ok: true, message: `Shifted subtitle by ${formatOffsetSummary(offsetMs)}`, }; } finally { - if (!keepTempTarget) { - cleanupTemporaryFile(targetExtraction); - } + cleanupTemporaryFile(targetExtraction); } } diff --git a/src/core/services/subsync.ts b/src/core/services/subsync.ts index 5ded8e2a..8d557d97 100644 --- a/src/core/services/subsync.ts +++ b/src/core/services/subsync.ts @@ -1,5 +1,6 @@ import { SubsyncManualRunRequest, SubsyncResult } from '../../types'; import { runAutoSubsync } from './subsync-auto'; +import { pruneRetainedSubsyncTempDirs } from './subsync-files'; import { openSubsyncManualPicker, runSubsyncManualUnguarded } from './subsync-manual'; import { PLAYBACK_CHANGED_RESULT_MESSAGE, @@ -14,11 +15,27 @@ import { export { openSubsyncManualPicker } from './subsync-manual'; export type { SubsyncVadPaths, TriggerSubsyncFromConfigDeps } from './subsync-shared'; +/** + * Before a run, drop temp dirs of earlier synced embedded/remote tracks that mpv no longer + * lists (e.g. after switching episodes). Skipped when the track list cannot be read. + */ +async function pruneTempDirsMpvNoLongerUses(deps: SubsyncCoreDeps): Promise { + const client = deps.getMpvClient(); + if (!client?.connected) return; + const trackList = await client.requestProperty('track-list').catch(() => null); + if (!Array.isArray(trackList)) return; + const referenced = trackList.flatMap((track: { 'external-filename'?: unknown } | null) => + typeof track?.['external-filename'] === 'string' ? [track['external-filename']] : [], + ); + pruneRetainedSubsyncTempDirs(referenced); +} + /** Manual (modal) run, cancelled when playback moves to other media. */ export async function runSubsyncManual( request: SubsyncManualRunRequest, deps: SubsyncCoreDeps, ): Promise { + await pruneTempDirsMpvNoLongerUses(deps); try { return await runWithMediaChangeAbort(deps, async (runDeps) => { const result = await runSubsyncManualUnguarded(request, runDeps); @@ -102,6 +119,7 @@ export async function triggerSubsyncFromConfig(deps: TriggerSubsyncFromConfigDep deps.setSubsyncInProgress(true); try { + await pruneTempDirsMpvNoLongerUses(deps); await runWithMediaChangeAbort(deps, async (runDeps) => { if (runDeps.getResolvedConfig().mode === 'manual') { const opened = await openSubsyncManualPicker(runDeps, { skipAudioAnalysis: true });