mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-28 04:46:07 -08:00
feat(subsync): keep a one-time backup when replacing subtitles in place
Auto mode rewrites the active subtitle from one keypress with replace on by default. The first in-place rewrite now copies the original to <file>.orig (not a subtitle extension, so mpv autoload and sidecar discovery skip it). Replacements also write through symlinks and keep the file's permissions.
This commit is contained in:
5 files changed
+128
-28
No files matched your search
@@ -3,3 +3,4 @@ area: subsync
|
||||
|
||||
- Integrated built-in alass-based subtitle syncing with sign/song stripping, framerate and scene-cut/ad-break handling, audio alignment verification across all loaded/embedded/sidecar tracks, and built-in speech-activity audio fallback.
|
||||
- Added one-click automatic syncing via the subtitle sidebar Sync button and `Ctrl+Alt+S` (`subsync.mode: "auto"`), automatically opening the guided Subtitle Sync modal with diagnostics, file browsing, external engine fallbacks, and manual offset only when guidance is needed.
|
||||
- In-place sync (`subsync.replace`, on by default) keeps the untouched original next to the subtitle as `<file>.orig` on the first overwrite.
|
||||
@@ -525,13 +525,13 @@ Built-in alass-based subtitle alignment works out of the box with no extra sync
|
||||
|
||||
Optional external [`alass`](https://github.com/kaegi/alass) and [`ffsubsync`](https://github.com/smacke/ffsubsync) binaries are also supported in the guided modal when installed.
|
||||
|
||||
| Key | Default | What it does |
|
||||
| ------------------------ | -------- | --------------------------------------------------------------------------------------------------------- |
|
||||
| `subsync.mode` | `"auto"` | `"auto"` syncs immediately and opens the guided modal only when needed; `"manual"` always opens the modal |
|
||||
| `subsync.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffmpeg_path` | `""` | `ffmpeg` path used to extract embedded tracks and audio speech. Empty auto-discovers from `PATH` |
|
||||
| `subsync.replace` | `true` | Overwrite the subtitle file. When off, write `<name>_retimed.<ext>` |
|
||||
| Key | Default | What it does |
|
||||
| ------------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `subsync.mode` | `"auto"` | `"auto"` syncs immediately and opens the guided modal only when needed; `"manual"` always opens the modal |
|
||||
| `subsync.alass_path` | `""` | Optional external `alass` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffsubsync_path` | `""` | Optional external `ffsubsync` path. Empty auto-discovers from `PATH` |
|
||||
| `subsync.ffmpeg_path` | `""` | `ffmpeg` path used to extract embedded tracks and audio speech. Empty auto-discovers from `PATH` |
|
||||
| `subsync.replace` | `true` | Overwrite the subtitle file, keeping the original as `<file>.orig` on the first overwrite. When off, write `<name>_retimed.<ext>` |
|
||||
|
||||
### AniList
|
||||
|
||||
|
||||
@@ -151,6 +151,8 @@ SubMiner includes a built-in alass-based aligner and speech-activity fallback (u
|
||||
- SubMiner pauses for guidance when confidence is low (for example, a mismatched episode), when a reference subtitle track is itself misaligned with the audio and audio-only alignment is uncertain, or when a remote stream has no usable reference track.
|
||||
- In the guided modal you can switch to another embedded/sidecar track, browse for a local reference subtitle file, switch to built-in video audio speech detection, toggle **Ignore signs & songs** or **Allow scene cuts & ad-break splits**, try external `alass`/`ffsubsync`, or apply a **Manual offset**.
|
||||
|
||||
**A sync made the timing worse**: the first in-place sync keeps the original as `<file>.orig` next to the subtitle. Rename it back over the subtitle to restore it.
|
||||
|
||||
**"Configured alass executable not found"** / **"Configured ffsubsync executable not found"**: only applies when selecting the optional external engines. Install them (`paru -S alass`, `cargo install alass-cli`, or `pip install ffsubsync`), set `subsync.alass_path` / `subsync.ffsubsync_path`, or use the **Built-in (alass)** engine.
|
||||
|
||||
**"alass synchronization failed" / "ffsubsync synchronization failed"**:
|
||||
|
||||
@@ -1545,6 +1545,69 @@ test('runSubsyncManual supports built-in file reference and manual offset engine
|
||||
assert.equal(offsetResult.message, 'Shifted subtitle by -1.25s');
|
||||
});
|
||||
|
||||
test('in-place replacement keeps a one-time .orig backup, the file mode, and symlinks', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-backup-'));
|
||||
const videoPath = path.join(tmpDir, 'ep01.mkv');
|
||||
const realTargetPath = path.join(tmpDir, 'store', 'ep01.ja.srt');
|
||||
const linkedTargetPath = path.join(tmpDir, 'ep01.ja.srt');
|
||||
fs.mkdirSync(path.dirname(realTargetPath));
|
||||
fs.writeFileSync(videoPath, 'video');
|
||||
writeSrtFromSpans(realTargetPath, generateSyntheticSpans(7n, 1442695040888963407n, 50), 0);
|
||||
fs.chmodSync(realTargetPath, 0o640);
|
||||
const original = fs.readFileSync(realTargetPath, 'utf8');
|
||||
const canSymlink = (() => {
|
||||
try {
|
||||
fs.symlinkSync(realTargetPath, linkedTargetPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
const targetPath = canSymlink ? linkedTargetPath : realTargetPath;
|
||||
|
||||
const deps = makeDeps({
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentAudioStreamIndex: null,
|
||||
send: () => {},
|
||||
requestProperty: async (name: string) => {
|
||||
if (name === 'path') return videoPath;
|
||||
if (name === 'sid') return 1;
|
||||
if (name === 'secondary-sid') return null;
|
||||
if (name === 'track-list') {
|
||||
return [
|
||||
{ id: 1, type: 'sub', selected: true, external: true, 'external-filename': targetPath },
|
||||
];
|
||||
}
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
getResolvedConfig: () => ({
|
||||
alassPath: '/missing/alass',
|
||||
ffsubsyncPath: '/missing/ffsubsync',
|
||||
ffmpegPath: '/missing/ffmpeg',
|
||||
replace: true,
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal((await runSubsyncManual({ engine: 'offset', offsetMs: 1000 }, deps)).ok, true);
|
||||
assert.equal((await runSubsyncManual({ engine: 'offset', offsetMs: 1000 }, deps)).ok, true);
|
||||
|
||||
const backupPath = `${realTargetPath}.orig`;
|
||||
assert.equal(fs.readFileSync(backupPath, 'utf8'), original);
|
||||
assert.notEqual(fs.readFileSync(realTargetPath, 'utf8'), original);
|
||||
if (process.platform !== 'win32') {
|
||||
assert.equal(fs.statSync(realTargetPath).mode & 0o777, 0o640);
|
||||
}
|
||||
if (canSymlink) {
|
||||
assert.equal(fs.lstatSync(linkedTargetPath).isSymbolicLink(), true);
|
||||
}
|
||||
assert.deepEqual(fs.readdirSync(path.dirname(realTargetPath)).sort(), [
|
||||
'ep01.ja.srt',
|
||||
'ep01.ja.srt.orig',
|
||||
]);
|
||||
});
|
||||
|
||||
test('runSubsyncManual rejects non-file references and keeps the track title and lang on reload', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subsync-manual-ref-validation-'));
|
||||
const videoPath = path.join(tmpDir, 'ep01.mkv');
|
||||
|
||||
@@ -500,23 +500,63 @@ function readAndParseSubtitleFile(filePath: string): ParsedSubtitleFile {
|
||||
};
|
||||
}
|
||||
|
||||
function writeRetimedContent(outputPath: string, content: string): void {
|
||||
const dir = path.dirname(outputPath);
|
||||
/** Suffix for the one-time backup of a replaced subtitle; not a subtitle extension, so mpv and sidecar discovery ignore it. */
|
||||
const SUBSYNC_BACKUP_SUFFIX = '.orig';
|
||||
|
||||
function resolveRealPathOrSelf(filePath: string): string {
|
||||
try {
|
||||
return fs.realpathSync(filePath);
|
||||
} catch {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a staged retimed file over `outputPath`. Writes through a symlink to the real file
|
||||
* and keeps its permissions. When `replacesSource` is set (in-place `subsync.replace`), the
|
||||
* first replacement keeps the untouched original as `<file>.orig`; later runs leave it alone.
|
||||
*/
|
||||
function installRetimedFile(stagedPath: string, outputPath: string, replacesSource: boolean): void {
|
||||
const targetPath = resolveRealPathOrSelf(outputPath);
|
||||
const existing = fs.existsSync(targetPath) ? fs.statSync(targetPath) : null;
|
||||
if (existing) {
|
||||
if (replacesSource) {
|
||||
const backupPath = `${targetPath}${SUBSYNC_BACKUP_SUFFIX}`;
|
||||
if (!fs.existsSync(backupPath)) {
|
||||
fs.copyFileSync(targetPath, backupPath, fs.constants.COPYFILE_EXCL);
|
||||
}
|
||||
}
|
||||
fs.chmodSync(stagedPath, existing.mode & 0o7777);
|
||||
}
|
||||
try {
|
||||
fs.renameSync(stagedPath, targetPath);
|
||||
} catch (error) {
|
||||
// A staged file next to a symlink can sit on another filesystem than the link target.
|
||||
if ((error as NodeJS.ErrnoException).code !== 'EXDEV') throw error;
|
||||
fs.copyFileSync(stagedPath, targetPath);
|
||||
fs.unlinkSync(stagedPath);
|
||||
}
|
||||
}
|
||||
|
||||
function removeIfExists(filePath: string): void {
|
||||
try {
|
||||
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
||||
} catch {
|
||||
// Best-effort cleanup of a staged write artifact.
|
||||
}
|
||||
}
|
||||
|
||||
function writeRetimedContent(outputPath: string, content: string, replacesSource: boolean): void {
|
||||
const dir = path.dirname(resolveRealPathOrSelf(outputPath));
|
||||
const tmpPath = path.join(
|
||||
dir,
|
||||
`.subminer-subsync-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`,
|
||||
);
|
||||
try {
|
||||
fs.writeFileSync(tmpPath, content, 'utf8');
|
||||
fs.renameSync(tmpPath, outputPath);
|
||||
installRetimedFile(tmpPath, outputPath, replacesSource);
|
||||
} catch (error) {
|
||||
try {
|
||||
if (fs.existsSync(tmpPath)) {
|
||||
fs.unlinkSync(tmpPath);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup of temp write artifact.
|
||||
}
|
||||
removeIfExists(tmpPath);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1221,7 +1261,7 @@ async function runBuiltinSubsync(
|
||||
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
|
||||
}
|
||||
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent);
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
|
||||
if (targetExtraction.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
@@ -1272,7 +1312,7 @@ async function runManualOffsetSubsync(
|
||||
if (!(await isPlaybackSessionUnchanged(client, context, targetTrack, targetSlot))) {
|
||||
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
|
||||
}
|
||||
writeRetimedContent(outputPath, rewritten);
|
||||
writeRetimedContent(outputPath, rewritten, replaceTarget);
|
||||
if (targetExtraction.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
@@ -1346,20 +1386,14 @@ async function subsyncToReference(
|
||||
return { ok: false, message: 'Playback changed while syncing; discarded stale result.' };
|
||||
}
|
||||
|
||||
fs.renameSync(stagedOutputPath, outputPath);
|
||||
installRetimedFile(stagedOutputPath, outputPath, replaceTarget);
|
||||
await loadSyncedSubtitle(client, outputPath, slot, targetTrack);
|
||||
return {
|
||||
ok: true,
|
||||
message: `Subtitle synchronized with ${engine}`,
|
||||
};
|
||||
} finally {
|
||||
try {
|
||||
if (fs.existsSync(stagedOutputPath)) {
|
||||
fs.unlinkSync(stagedOutputPath);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup of staged external-engine output.
|
||||
}
|
||||
removeIfExists(stagedOutputPath);
|
||||
cleanupTemporaryFile(targetExtraction);
|
||||
}
|
||||
}
|
||||
@@ -1900,7 +1934,7 @@ async function runAutoSubsync(deps: TriggerSubsyncFromConfigDeps): Promise<void>
|
||||
deps.showMpvOsd(`Subsync failed: ${LOSSY_REWRITE_ERROR_MESSAGE}`);
|
||||
return;
|
||||
}
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent);
|
||||
writeRetimedContent(outputPath, alignment.rewrittenContent, replaceTarget);
|
||||
if (targetExtraction!.temporary) {
|
||||
keepTempTarget = true;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user