mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-09-10 17:16:20 -07:00
Compare commits
7
Commits
760b3e1d3d
...
8e47e0d761
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e47e0d761
|
||
|
|
dcd05ee4ea
|
||
|
|
99266294b8 | ||
|
|
c055359be1
|
||
|
|
56a2a25312
|
||
|
|
c85db5e07e
|
||
|
|
f90ee78204
|
@@ -38,7 +38,7 @@
|
||||
"app-builder-lib": "26.15.3",
|
||||
"brace-expansion": "5.0.9",
|
||||
"electron-builder-squirrel-windows": "26.15.3",
|
||||
"fast-uri": "3.1.5",
|
||||
"fast-uri": "3.1.6",
|
||||
"form-data": "4.0.6",
|
||||
"ip-address": "10.2.0",
|
||||
"js-yaml": "4.3.1",
|
||||
@@ -406,7 +406,7 @@
|
||||
|
||||
"fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
|
||||
|
||||
"fast-uri": ["fast-uri@3.1.5", "", {}, "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw=="],
|
||||
"fast-uri": ["fast-uri@3.1.6", "", {}, "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q=="],
|
||||
|
||||
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
type: added
|
||||
area: mining
|
||||
|
||||
- Added optional pre-generation timing review for word, sentence, and audio cards with a compact speech-weighted waveform, clearly labeled mined-line boundaries, drag and keyboard adjustments, audio preview with a sweeping playhead, exact screenshot and AVIF timing, cancellation choices that include keeping a card without media, and a session-only runtime toggle.
|
||||
- Added optional pre-generation timing review for word, sentence, and audio cards with a compact speech-weighted waveform that flattens steady background noise so dialogue edges are easy to see, clearly labeled mined-line boundaries, a clip end that moves back to where the line's dialogue actually ends once the waveform loads (subtitles usually linger past speech), drag and keyboard adjustments, audio preview with a sweeping playhead that plays the clip to its true end even on high-latency outputs such as Bluetooth headphones, exact screenshot and AVIF timing, cancellation choices that include keeping a card without media, and a session-only runtime toggle.
|
||||
- The timing review can pull any number of previous and next subtitle lines onto the card: `P`/`N` (or the Prev/Next steppers) add lines one at a time, Shift removes them, the sentence preview highlights exactly what the card will contain, and the clip range and line boundary markers on the waveform follow the added lines automatically.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
type: fixed
|
||||
area: mining
|
||||
|
||||
- Mining from the overlay no longer copies a lingering row of the previous broadcast caption onto the card sentence. The mined line and its clip timing now come from the parsed cue the overlay is showing, falling back to mpv's live text only when the cue list cannot explain it.
|
||||
@@ -0,0 +1,4 @@
|
||||
type: changed
|
||||
area: mining
|
||||
|
||||
- Mining a card from a remote stream (Jellyfin and other HTTP sources) now downloads the clip window once into a temporary file and reuses it for the timing review waveform, audio preview, audio extraction, and screenshot, instead of re-fetching the stream for every step. The temporary window is removed after ten minutes without use or on exit.
|
||||
@@ -0,0 +1,4 @@
|
||||
type: changed
|
||||
area: overlay
|
||||
|
||||
- The TsukiHime modal's Japanese and secondary-language tabs now filter the release list by the subtitle languages each release carries, and report when no release has subtitles for the active tab.
|
||||
@@ -158,6 +158,8 @@ If you only want sentence and audio on your cards:
|
||||
|
||||
SubMiner uses FFmpeg to generate audio and image media from the video. FFmpeg must be installed and on `PATH`.
|
||||
|
||||
For remote streams such as Jellyfin playback, SubMiner downloads the clip's time window once into a temporary Matroska file (a stream copy, no re-encoding) and reads the timing review waveform, audio preview, audio, and image from that file instead of fetching the stream again for each step. The window covers the clip plus padding, plus the visible timeline in timing review, and grows when you reveal more of the timeline. It is deleted when a different window replaces it, after ten minutes without use, or when SubMiner exits. If the download fails, media generation reads the remote stream directly as before.
|
||||
|
||||
### Audio
|
||||
|
||||
Audio is extracted from the video file using the subtitle's start and end timestamps. Padding is opt-in; keep it at `0` when you want sentence audio to start exactly at the mined sentence.
|
||||
@@ -181,7 +183,7 @@ Output format: MP3 at 44100 Hz. If the video has multiple audio streams, SubMine
|
||||
|
||||
The audio is uploaded to Anki's media folder and inserted as `[sound:audio_<timestamp>.mp3]`.
|
||||
|
||||
Set `media.reviewTiming` to `true` to pause playback and review each word, sentence, or audio card before its media is generated. The review opens with the subtitle range plus configured audio padding. Drag either edge of the clip to trim it, drag the middle to slide it without changing its length, or press anywhere else on the waveform to snap the nearer edge there. A focused edge also moves with the arrow keys, by 100 ms alone or 500 ms with Shift, and the 100 ms buttons do the same. Space previews the selection with a playhead that sweeps the clip, Enter confirms, and Escape cancels. The Earlier and Later buttons reveal another two seconds of available timeline without moving the selected clip. A speech-weighted waveform shows the mined subtitle as a tinted band with labeled line-start and line-end rails, making adjacent dialogue easier to distinguish. SubMiner uses a center channel when one carries dialogue, then falls back to a speech-band mono mix. Waveform analysis failure leaves the timing controls available. The confirmed range is exact: SubMiner does not apply audio padding a second time. Static screenshots use its midpoint, and animated AVIF clips use the full confirmed range.
|
||||
Set `media.reviewTiming` to `true` to pause playback and review each word, sentence, or audio card before its media is generated. The review opens with the subtitle range plus configured audio padding. Subtitles usually linger past the dialogue, so once the waveform loads an untouched clip end moves back to just after the line's last speech (plus the configured padding); the Line end rail keeps marking the subtitle timing, Reset restores it, and a line whose speech runs through its end is left alone. Drag either edge of the clip to trim it, drag the middle to slide it without changing its length, or press anywhere else on the waveform to snap the nearer edge there. A focused edge also moves with the arrow keys, by 100 ms alone or 500 ms with Shift, and the 100 ms buttons do the same. Space previews the selection with a playhead that sweeps the clip; the preview ends when the hidden player has actually played the last sample, so output latency such as Bluetooth headphones does not cut the clip short. Enter confirms, and Escape cancels. The Earlier and Later buttons reveal another two seconds of available timeline without moving the selected clip. A speech-weighted waveform shows the mined subtitle as a tinted band with labeled line-start and line-end rails, making adjacent dialogue easier to distinguish. SubMiner uses a center channel when one carries dialogue, then falls back to a mono mix, keeps only the 250 to 3500 Hz speech band, and draws each slice's loudness relative to the clip's own noise floor, so steady background music or ambience reads as a flat line while dialogue stands out. Waveform analysis failure leaves the timing controls available. The confirmed range is exact: SubMiner does not apply audio padding a second time. Static screenshots use its midpoint, and animated AVIF clips use the full confirmed range.
|
||||
|
||||
The review can also pull adjacent subtitle lines onto the card. Press `P` or `N` (or use the Prev and Next steppers above the sentence preview) to add the previous or next line, as many times as lines are available; Shift+`P` and Shift+`N` remove them again. The sentence preview lists every included line with the mined line highlighted, so the card's sentence field is always visible before you confirm, and the clip start or end, along with the line-start and line-end rails on the waveform, follows the outermost added line, keeping the review's audio padding. Confirming writes the combined lines to the sentence field; the Reset button drops the added lines along with any timing changes. Adjacent lines come from the parsed subtitle track when one is loaded; otherwise only lines that already played are offered, and a clip capped by `media.maxMediaDuration` keeps the full combined sentence even when the audio cannot cover every added line.
|
||||
|
||||
@@ -351,11 +353,11 @@ For Senren note types, enable `isSenren` instead. Kiku and Senren write incompat
|
||||
|
||||
### What Gets Merged
|
||||
|
||||
| Field | Merge behavior |
|
||||
| -------- | --------------------------------------------- |
|
||||
| Sentence | Both cards' sentences kept as grouped entries |
|
||||
| Audio | Both cards' `[sound:...]` entries kept |
|
||||
| Image | Both cards' images kept |
|
||||
| Field | Merge behavior |
|
||||
| -------- | ----------------------------------------------- |
|
||||
| Sentence | Both cards' sentences kept as grouped entries |
|
||||
| Audio | Both cards' `[sound:...]` entries kept |
|
||||
| Image | Both cards' images kept |
|
||||
| MiscInfo | Both cards' source info kept as grouped entries |
|
||||
|
||||
Identical values from both cards are kept as separate grouped entries; the merge does not deduplicate.
|
||||
|
||||
@@ -14,7 +14,7 @@ Unlike Jimaku, TsukiHime needs no account or API key. The only requirement is th
|
||||
|
||||
## How It Works
|
||||
|
||||
The integration runs through an in-overlay modal opened with `Ctrl+Shift+T` by default. The modal has two tabs that filter the subtitle tracks of the selected release by role: the first follows `secondarySub.secondarySubLanguages` (English when unset), and the second is always **Japanese**, the currently supported primary subtitle language. Tracks with no language tag stay visible on the secondary tab.
|
||||
The integration runs through an in-overlay modal opened with `Ctrl+Shift+T` by default. The modal has two tabs that filter both the release list and the subtitle tracks of the selected release by role: the first follows `secondarySub.secondarySubLanguages` (English when unset), and the second is always **Japanese**, the currently supported primary subtitle language. Each tab lists only the releases whose reported subtitle languages include the tab's language, so the Japanese tab hides the many releases that ship English subtitles only. Releases and tracks with no language tag stay visible on the secondary tab. If nothing on the active tab qualifies, the status line says so and points at the other tab.
|
||||
|
||||
When you open the modal, SubMiner parses the current video filename to extract a title and episode number (same parser as Jimaku - `S01E03`, `1x03`, `E03`, and dash-separated numbers all work). If the filename yields a high-confidence match, SubMiner auto-searches immediately.
|
||||
|
||||
@@ -76,6 +76,7 @@ The previous `--open-animetosho` flag and `__animetosho-open` keybinding command
|
||||
## Troubleshooting
|
||||
|
||||
- **"xz binary not found"** - install `xz`/`xz-utils` with your package manager.
|
||||
- **"No releases with Japanese subtitles"** - none of the search results carry a Japanese track. Most releases only ship English subtitles; try another search, or use the [Jimaku integration](/jimaku-integration) for Japanese subtitles.
|
||||
- **"Batch releases are not supported"** - TsukiHime only exposes extracted attachments for single-file torrents. Pick the single-episode release for your episode instead of a season batch.
|
||||
- **"No text subtitle tracks in this release"** - the release only carries image-based subtitles (PGS/VobSub) or none at all; try a different release (fansub and SubsPlease-style releases almost always carry ASS tracks).
|
||||
- **Timing is off** - the subtitle came from a different release than your video file. Use the subtitle sync modal (`Ctrl+Alt+S`) or pick the release matching your file exactly.
|
||||
|
||||
+1
-1
@@ -87,7 +87,7 @@
|
||||
"app-builder-lib": "26.15.3",
|
||||
"brace-expansion": "5.0.9",
|
||||
"electron-builder-squirrel-windows": "26.15.3",
|
||||
"fast-uri": "3.1.5",
|
||||
"fast-uri": "3.1.6",
|
||||
"form-data": "4.0.6",
|
||||
"ip-address": "10.2.0",
|
||||
"js-yaml": "4.3.1",
|
||||
|
||||
@@ -23,6 +23,21 @@ describe('buildMediaTimingPreviewArgs', () => {
|
||||
assert.equal(args.at(-1), '/video/show.mkv');
|
||||
});
|
||||
|
||||
test('keeps source timestamps for cached remote windows', () => {
|
||||
const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
|
||||
mediaPath: '/tmp/window.mkv',
|
||||
absoluteTimestamps: true,
|
||||
});
|
||||
|
||||
assert.ok(args.includes('--rebase-start-time=no'));
|
||||
assert.equal(
|
||||
buildMediaTimingPreviewArgs('/tmp/review.sock', { mediaPath: '/video/show.mkv' }).includes(
|
||||
'--rebase-start-time=no',
|
||||
),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('separates an option-like media path without adding optional audio arguments', () => {
|
||||
const args = buildMediaTimingPreviewArgs('/tmp/review.sock', {
|
||||
mediaPath: '--fullscreen',
|
||||
@@ -189,3 +204,88 @@ test('preview session bounds a connection attempt that never settles', async ()
|
||||
await assert.rejects(session.start({ mediaPath: '/video/show.mkv' }), /Timed out starting/);
|
||||
assert.equal(connectAttempts, 1);
|
||||
});
|
||||
|
||||
function createFakeSocket() {
|
||||
const socket = new EventEmitter() as EventEmitter & {
|
||||
destroyed: boolean;
|
||||
write: (data: string) => boolean;
|
||||
end: () => void;
|
||||
destroy: () => void;
|
||||
off: EventEmitter['off'];
|
||||
};
|
||||
const writes: string[] = [];
|
||||
socket.destroyed = false;
|
||||
socket.write = (data) => {
|
||||
writes.push(data);
|
||||
return true;
|
||||
};
|
||||
socket.end = () => undefined;
|
||||
socket.destroy = () => {
|
||||
socket.destroyed = true;
|
||||
};
|
||||
return { socket, writes };
|
||||
}
|
||||
|
||||
test('preview session plays once to the clip end and reports when mpv has drained it', async () => {
|
||||
const { socket, writes } = createFakeSocket();
|
||||
const child = new EventEmitter() as EventEmitter & { kill: () => boolean };
|
||||
child.kill = () => true;
|
||||
const session = new MediaTimingPreviewSession({
|
||||
platform: 'linux',
|
||||
spawnProcess: () => child as never,
|
||||
connectSocket: () => {
|
||||
queueMicrotask(() => socket.emit('connect'));
|
||||
return socket as never;
|
||||
},
|
||||
removeSocketFile: () => undefined,
|
||||
createSocketPath: () => '/tmp/review.sock',
|
||||
});
|
||||
let endedCount = 0;
|
||||
session.onPlaybackEnded(() => {
|
||||
endedCount += 1;
|
||||
});
|
||||
const property = (name: string, data: boolean): string =>
|
||||
`${JSON.stringify({ event: 'property-change', name, data })}\n`;
|
||||
|
||||
await session.start({ mediaPath: '/video/show.mkv' });
|
||||
assert.deepEqual(
|
||||
writes.map((line) => JSON.parse(line).command),
|
||||
[
|
||||
['observe_property', 1, 'eof-reached'],
|
||||
['observe_property', 2, 'pause'],
|
||||
],
|
||||
);
|
||||
// The observers' initial replies describe the idle paused player, not a finished preview.
|
||||
socket.emit('data', property('eof-reached', false) + property('pause', true));
|
||||
assert.equal(endedCount, 0);
|
||||
|
||||
writes.length = 0;
|
||||
await session.play(12.25, 14.5);
|
||||
assert.deepEqual(
|
||||
writes.map((line) => JSON.parse(line).command),
|
||||
[
|
||||
['set_property', 'pause', true],
|
||||
['seek', 12.25, 'absolute+exact'],
|
||||
['set_property', 'end', '14.500'],
|
||||
['set_property', 'pause', false],
|
||||
],
|
||||
);
|
||||
|
||||
// Events may arrive split across chunks. The decoder passing `end` flips eof-reached while
|
||||
// audio still drains; only the keep-open pause that follows marks the preview as finished.
|
||||
socket.emit('data', property('eof-reached', false) + property('pause', false).slice(0, 20));
|
||||
socket.emit('data', property('pause', false).slice(20) + property('eof-reached', true));
|
||||
assert.equal(endedCount, 0);
|
||||
socket.emit('data', property('pause', true));
|
||||
assert.equal(endedCount, 1);
|
||||
socket.emit('data', property('pause', true));
|
||||
assert.equal(endedCount, 1);
|
||||
|
||||
// Stopping early pauses without an end signal, and a later real EOF is not a preview end.
|
||||
await session.play(1, 2);
|
||||
socket.emit('data', property('eof-reached', false) + property('pause', false));
|
||||
await session.stop();
|
||||
socket.emit('data', property('pause', true) + property('eof-reached', true));
|
||||
assert.equal(endedCount, 1);
|
||||
session.dispose();
|
||||
});
|
||||
|
||||
@@ -8,12 +8,21 @@ import { randomUUID } from 'crypto';
|
||||
const CONNECT_TIMEOUT_MS = 5_000;
|
||||
const CONNECT_ATTEMPT_TIMEOUT_MS = 500;
|
||||
const CONNECT_RETRY_MS = 40;
|
||||
/**
|
||||
* mpv flips eof-reached as soon as the decoder passes `end`, while its audio buffer is still
|
||||
* draining; keep-open then pauses once the buffer has played out. A preview has ended when
|
||||
* both have happened.
|
||||
*/
|
||||
const EOF_OBSERVER_ID = 1;
|
||||
const PAUSE_OBSERVER_ID = 2;
|
||||
|
||||
export interface MediaTimingPreviewStartOptions {
|
||||
mediaPath: string;
|
||||
executablePath?: string;
|
||||
audioTrackId?: number;
|
||||
volume?: number;
|
||||
/** The file keeps source timestamps (a cached remote window); seek with the original times. */
|
||||
absoluteTimestamps?: boolean;
|
||||
}
|
||||
|
||||
type PreviewProcess = Pick<ChildProcess, 'kill' | 'once'>;
|
||||
@@ -51,6 +60,9 @@ export function buildMediaTimingPreviewArgs(
|
||||
if (typeof options.volume === 'number' && Number.isFinite(options.volume)) {
|
||||
args.push(`--volume=${Math.max(0, options.volume)}`);
|
||||
}
|
||||
if (options.absoluteTimestamps) {
|
||||
args.push('--rebase-start-time=no');
|
||||
}
|
||||
args.push('--', options.mediaPath);
|
||||
return args;
|
||||
}
|
||||
@@ -89,6 +101,11 @@ export class MediaTimingPreviewSession {
|
||||
resolve: () => void;
|
||||
} | null = null;
|
||||
private disposed = false;
|
||||
private readBuffer = '';
|
||||
private playing = false;
|
||||
private eofReached = false;
|
||||
private paused = true;
|
||||
private readonly endedListeners = new Set<() => void>();
|
||||
|
||||
constructor(deps: Partial<MediaTimingPreviewDeps> = {}) {
|
||||
this.deps = {
|
||||
@@ -155,6 +172,11 @@ export class MediaTimingPreviewSession {
|
||||
await this.connectWithRetry(socketPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plays [startTime, endTime) once. mpv stops itself at `end` and, thanks to keep-open,
|
||||
* pauses after draining the audio device, so the listener hears the whole clip even on
|
||||
* high-latency outputs. onPlaybackEnded fires when mpv reports the end was reached.
|
||||
*/
|
||||
async play(startTime: number, endTime: number): Promise<void> {
|
||||
if (!this.socket || this.socket.destroyed) {
|
||||
throw new Error('Preview player is not ready');
|
||||
@@ -163,18 +185,68 @@ export class MediaTimingPreviewSession {
|
||||
throw new Error('Preview timing is invalid');
|
||||
}
|
||||
|
||||
this.playing = false;
|
||||
this.send(['set_property', 'pause', true]);
|
||||
this.send(['set_property', 'ab-loop-a', startTime]);
|
||||
this.send(['set_property', 'ab-loop-b', endTime]);
|
||||
this.send(['seek', startTime, 'absolute+exact']);
|
||||
// The option parser wants a time string; a raw JSON number is not accepted for `end`.
|
||||
this.send(['set_property', 'end', endTime.toFixed(3)]);
|
||||
this.send(['set_property', 'pause', false]);
|
||||
// Only the seek's eof-reached=false and the later keep-open pause count for this play.
|
||||
this.eofReached = false;
|
||||
this.paused = false;
|
||||
this.playing = true;
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.playing = false;
|
||||
if (!this.socket || this.socket.destroyed) return;
|
||||
this.send(['set_property', 'pause', true]);
|
||||
}
|
||||
|
||||
onPlaybackEnded(listener: () => void): void {
|
||||
this.endedListeners.add(listener);
|
||||
}
|
||||
|
||||
private finishPlayback(): void {
|
||||
if (!this.playing) return;
|
||||
this.playing = false;
|
||||
for (const listener of this.endedListeners) listener();
|
||||
}
|
||||
|
||||
private handleSocketData(chunk: Buffer | string): void {
|
||||
this.readBuffer += chunk.toString();
|
||||
let newline = this.readBuffer.indexOf('\n');
|
||||
while (newline !== -1) {
|
||||
const line = this.readBuffer.slice(0, newline).trim();
|
||||
this.readBuffer = this.readBuffer.slice(newline + 1);
|
||||
newline = this.readBuffer.indexOf('\n');
|
||||
if (!line) continue;
|
||||
let message: unknown;
|
||||
try {
|
||||
message = JSON.parse(line);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof message === 'object' &&
|
||||
message !== null &&
|
||||
'event' in message &&
|
||||
message.event === 'property-change' &&
|
||||
'name' in message &&
|
||||
'data' in message
|
||||
) {
|
||||
this.handlePropertyChange(message.name, message.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handlePropertyChange(name: unknown, data: unknown): void {
|
||||
if (name === 'eof-reached') this.eofReached = data === true;
|
||||
else if (name === 'pause') this.paused = data === true;
|
||||
else return;
|
||||
if (this.playing && this.eofReached && this.paused) this.finishPlayback();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
@@ -229,6 +301,13 @@ export class MediaTimingPreviewSession {
|
||||
throw new Error('Preview session is closed');
|
||||
}
|
||||
this.socket = socket;
|
||||
this.readBuffer = '';
|
||||
socket.on('data', (chunk: Buffer | string) => {
|
||||
if (this.socket === socket) this.handleSocketData(chunk);
|
||||
});
|
||||
socket.once('close', () => this.finishPlayback());
|
||||
this.send(['observe_property', EOF_OBSERVER_ID, 'eof-reached']);
|
||||
this.send(['observe_property', PAUSE_OBSERVER_ID, 'pause']);
|
||||
return;
|
||||
} catch {
|
||||
if (this.disposed) {
|
||||
|
||||
@@ -35,16 +35,67 @@ test('speech waveform maps the selected FFmpeg stream and visible range', () =>
|
||||
assert.match(args[args.indexOf('-af') + 1] ?? '', /c0=FC/);
|
||||
});
|
||||
|
||||
test('waveform peaks are normalized without flattening quieter sections', () => {
|
||||
test('speech waveform seeks cached windows by source timestamps', () => {
|
||||
const args = buildSpeechWaveformArgs(
|
||||
{
|
||||
mediaPath: { path: '/tmp/window.mkv', absoluteTimestamps: true, singleResolvedStream: true },
|
||||
startTime: 8,
|
||||
endTime: 15,
|
||||
},
|
||||
'downmix',
|
||||
);
|
||||
|
||||
assert.deepEqual(args.slice(args.indexOf('-ss'), args.indexOf('-t') + 2), [
|
||||
'-ss',
|
||||
'8',
|
||||
'-seek_timestamp',
|
||||
'1',
|
||||
'-i',
|
||||
'/tmp/window.mkv',
|
||||
'-t',
|
||||
'7',
|
||||
]);
|
||||
assert.equal(args.includes('-map'), false);
|
||||
});
|
||||
|
||||
test('waveform levels rise with loudness and top out at the reference level', () => {
|
||||
const peaks = computeWaveformPeaks(pcm([0, 1_000, -2_000, 4_000, -8_000, 16_000]), 3);
|
||||
|
||||
assert.equal(peaks.length, 3);
|
||||
assert.ok((peaks[0] ?? 0) > 0);
|
||||
assert.ok((peaks[0] ?? 0) < (peaks[1] ?? 0));
|
||||
assert.equal(peaks[0], 0);
|
||||
assert.ok((peaks[1] ?? 0) > 0);
|
||||
assert.ok((peaks[1] ?? 0) < (peaks[2] ?? 0));
|
||||
assert.equal(peaks[2], 1);
|
||||
});
|
||||
|
||||
test('waveform flattens steady background noise and keeps speech bursts tall', () => {
|
||||
// 20 slices of steady noise at a fixed level with an 18 dB louder "speech" burst in the middle.
|
||||
const noise = 1_000;
|
||||
const samples: number[] = [];
|
||||
for (let slice = 0; slice < 20; slice += 1) {
|
||||
const level = slice >= 8 && slice < 12 ? noise * 8 : noise;
|
||||
for (let sample = 0; sample < 50; sample += 1) {
|
||||
samples.push(sample % 2 === 0 ? level : -level);
|
||||
}
|
||||
}
|
||||
|
||||
const peaks = computeWaveformPeaks(pcm(samples), 20);
|
||||
|
||||
for (const [index, peak] of peaks.entries()) {
|
||||
if (index >= 8 && index < 12) assert.equal(peak, 1);
|
||||
else assert.equal(peak, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('waveform stays flat when the whole range is a single steady level', () => {
|
||||
const peaks = computeWaveformPeaks(
|
||||
pcm(Array.from({ length: 400 }, (_, i) => (i % 2 ? 900 : -900))),
|
||||
40,
|
||||
);
|
||||
|
||||
assert.ok(peaks.every((peak) => peak === 0));
|
||||
});
|
||||
|
||||
test('speech waveform uses a mono downmix when the source has no center activity', async () => {
|
||||
const calls: string[][] = [];
|
||||
const peaks = await generateSpeechWaveform(
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { normalizeMediaInput, type MediaInput } from '../../media-input';
|
||||
|
||||
const WAVEFORM_SAMPLE_RATE = 8_000;
|
||||
const WAVEFORM_POINT_COUNT = 480;
|
||||
const WAVEFORM_TIMEOUT_MS = 15_000;
|
||||
const MAX_WAVEFORM_BYTES = 16 * 1024 * 1024;
|
||||
const SPEECH_FILTER = 'highpass=f=120,lowpass=f=4000';
|
||||
// Keep the band where speech intelligibility lives; bass, drums, and hum sit below it.
|
||||
const SPEECH_FILTER = 'highpass=f=250,lowpass=f=3500';
|
||||
const NOISE_FLOOR_PERCENTILE = 0.2;
|
||||
const REFERENCE_PERCENTILE = 0.95;
|
||||
const NOISE_GATE_DB = 3;
|
||||
const MIN_DISPLAY_RANGE_DB = 12;
|
||||
const SILENCE_DB = -100;
|
||||
const CENTER_CHANNEL_FILTER = `pan=mono|c0=FC,${SPEECH_FILTER}`;
|
||||
const DOWNMIX_FILTER = `aformat=channel_layouts=mono,${SPEECH_FILTER}`;
|
||||
|
||||
export interface SpeechWaveformOptions {
|
||||
mediaPath: string;
|
||||
mediaPath: MediaInput;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
audioStreamIndex?: number;
|
||||
@@ -22,6 +29,7 @@ export function buildSpeechWaveformArgs(
|
||||
mode: 'center' | 'downmix',
|
||||
): string[] {
|
||||
const duration = options.endTime - options.startTime;
|
||||
const input = normalizeMediaInput(options.mediaPath);
|
||||
const args = [
|
||||
'-hide_banner',
|
||||
'-nostdin',
|
||||
@@ -29,8 +37,9 @@ export function buildSpeechWaveformArgs(
|
||||
'error',
|
||||
'-ss',
|
||||
String(options.startTime),
|
||||
...input.inputArgs,
|
||||
'-i',
|
||||
options.mediaPath,
|
||||
input.path,
|
||||
'-t',
|
||||
String(duration),
|
||||
];
|
||||
@@ -108,11 +117,22 @@ function runFfmpeg(args: string[]): Promise<Buffer> {
|
||||
});
|
||||
}
|
||||
|
||||
function percentile(sortedValues: number[], fraction: number): number {
|
||||
const index = Math.min(sortedValues.length - 1, Math.floor(sortedValues.length * fraction));
|
||||
return sortedValues[index] ?? SILENCE_DB;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns mono PCM into 0..1 display heights. Each point is the RMS level of its slice in
|
||||
* dB, measured against the clip's own noise floor (a low percentile of the slices), so
|
||||
* constant background noise draws flat and sustained speech stands out. Peak sampling
|
||||
* would instead follow music transients and lift the floor to nearly speech height.
|
||||
*/
|
||||
export function computeWaveformPeaks(pcm: Buffer, pointCount = WAVEFORM_POINT_COUNT): number[] {
|
||||
const sampleCount = Math.floor(pcm.byteLength / 2);
|
||||
if (sampleCount === 0 || pointCount <= 0) return [];
|
||||
const resolvedPointCount = Math.min(pointCount, sampleCount);
|
||||
const peaks = Array.from({ length: resolvedPointCount }, () => 0);
|
||||
const levelsDb = Array.from({ length: resolvedPointCount }, () => SILENCE_DB);
|
||||
|
||||
for (let point = 0; point < resolvedPointCount; point += 1) {
|
||||
const sampleStart = Math.floor((point * sampleCount) / resolvedPointCount);
|
||||
@@ -120,18 +140,25 @@ export function computeWaveformPeaks(pcm: Buffer, pointCount = WAVEFORM_POINT_CO
|
||||
sampleStart + 1,
|
||||
Math.floor(((point + 1) * sampleCount) / resolvedPointCount),
|
||||
);
|
||||
let peak = 0;
|
||||
let energy = 0;
|
||||
for (let sample = sampleStart; sample < sampleEnd; sample += 1) {
|
||||
peak = Math.max(peak, Math.abs(pcm.readInt16LE(sample * 2)) / 32_768);
|
||||
const value = pcm.readInt16LE(sample * 2) / 32_768;
|
||||
energy += value * value;
|
||||
}
|
||||
peaks[point] = peak;
|
||||
const rms = Math.sqrt(energy / (sampleEnd - sampleStart));
|
||||
levelsDb[point] = rms > 0 ? Math.max(SILENCE_DB, 20 * Math.log10(rms)) : SILENCE_DB;
|
||||
}
|
||||
|
||||
const sortedPeaks = [...peaks].sort((left, right) => left - right);
|
||||
const referenceIndex = Math.min(sortedPeaks.length - 1, Math.floor(sortedPeaks.length * 0.95));
|
||||
const referencePeak = Math.max(sortedPeaks[referenceIndex] ?? 0, 0.01);
|
||||
return peaks.map(
|
||||
(peak) => Math.round(Math.sqrt(Math.min(1, peak / referencePeak)) * 1_000) / 1_000,
|
||||
const sortedLevels = [...levelsDb].sort((left, right) => left - right);
|
||||
const floorDb = percentile(sortedLevels, NOISE_FLOOR_PERCENTILE) + NOISE_GATE_DB;
|
||||
const referenceDb = Math.max(
|
||||
percentile(sortedLevels, REFERENCE_PERCENTILE),
|
||||
floorDb + MIN_DISPLAY_RANGE_DB,
|
||||
);
|
||||
return levelsDb.map(
|
||||
(levelDb) =>
|
||||
Math.round(Math.min(1, Math.max(0, (levelDb - floorDb) / (referenceDb - floorDb))) * 1_000) /
|
||||
1_000,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildRemoteMediaWindowArgs,
|
||||
RemoteMediaWindowCache,
|
||||
REMOTE_MEDIA_WINDOW_MAX_SECONDS,
|
||||
type RemoteMediaWindowCacheOptions,
|
||||
} from './remote-media-window-cache';
|
||||
|
||||
const SOURCE = {
|
||||
path: 'https://jellyfin.example/Videos/abc/stream?static=true',
|
||||
audioStreamIndex: 2,
|
||||
};
|
||||
|
||||
type ExecFileStub = NonNullable<RemoteMediaWindowCacheOptions['execFile']>;
|
||||
|
||||
function createStub(options: { fail?: boolean; empty?: boolean; defer?: boolean } = {}) {
|
||||
const calls: string[][] = [];
|
||||
const pendingCallbacks: Array<() => void> = [];
|
||||
const execFile: ExecFileStub = (_file, args, _options, callback) => {
|
||||
calls.push([...args]);
|
||||
const finish = (): void => {
|
||||
const outputPath = args.at(-1);
|
||||
assert.ok(outputPath);
|
||||
if (options.fail) {
|
||||
callback(Object.assign(new Error('boom'), { code: 1 }));
|
||||
return;
|
||||
}
|
||||
if (!options.empty) {
|
||||
fs.writeFileSync(outputPath, 'mkv', 'utf8');
|
||||
}
|
||||
callback(null);
|
||||
};
|
||||
if (options.defer) {
|
||||
pendingCallbacks.push(finish);
|
||||
} else {
|
||||
queueMicrotask(finish);
|
||||
}
|
||||
};
|
||||
return {
|
||||
calls,
|
||||
execFile,
|
||||
flush: () => {
|
||||
for (const finish of pendingCallbacks.splice(0)) finish();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function withCache(
|
||||
stubOptions: Parameters<typeof createStub>[0],
|
||||
cacheOptions: Omit<RemoteMediaWindowCacheOptions, 'execFile' | 'tempDir'>,
|
||||
run: (cache: RemoteMediaWindowCache, stub: ReturnType<typeof createStub>) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-media-window-test-'));
|
||||
const stub = createStub(stubOptions);
|
||||
const cache = new RemoteMediaWindowCache({
|
||||
tempDir,
|
||||
execFile: stub.execFile,
|
||||
idleTtlMs: 0,
|
||||
logDebug: () => undefined,
|
||||
...cacheOptions,
|
||||
});
|
||||
try {
|
||||
await run(cache, stub);
|
||||
} finally {
|
||||
cache.cleanup();
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function argValue(args: string[], flag: string): string | undefined {
|
||||
const index = args.indexOf(flag);
|
||||
return index === -1 ? undefined : args[index + 1];
|
||||
}
|
||||
|
||||
test('buildRemoteMediaWindowArgs stream-copies the window with source timestamps intact', () => {
|
||||
const args = buildRemoteMediaWindowArgs(
|
||||
{ ...SOURCE, inputOptions: { reconnect: true, headers: { Referer: 'https://a.example/' } } },
|
||||
{ startTime: 22.75, endTime: 33 },
|
||||
'/tmp/window.mkv',
|
||||
);
|
||||
|
||||
const inputIndex = args.indexOf('-i');
|
||||
assert.equal(args[inputIndex + 1], SOURCE.path);
|
||||
assert.ok(args.indexOf('-reconnect') < inputIndex);
|
||||
assert.ok(args.indexOf('-headers') < inputIndex);
|
||||
assert.equal(argValue(args, '-ss'), '22.75');
|
||||
assert.equal(argValue(args, '-t'), '10.25');
|
||||
assert.ok(args.indexOf('-t') < inputIndex);
|
||||
assert.deepEqual(args.slice(args.indexOf('-map'), args.indexOf('-map') + 4), [
|
||||
'-map',
|
||||
'0:v:0?',
|
||||
'-map',
|
||||
'0:2',
|
||||
]);
|
||||
assert.equal(argValue(args, '-c'), 'copy');
|
||||
assert.ok(args.includes('-copyts'));
|
||||
assert.ok(args.includes('-start_at_zero'));
|
||||
assert.equal(argValue(args, '-f'), 'matroska');
|
||||
assert.equal(args.at(-1), '/tmp/window.mkv');
|
||||
});
|
||||
|
||||
test('buildRemoteMediaWindowArgs keeps every audio stream when none is selected', () => {
|
||||
const args = buildRemoteMediaWindowArgs(
|
||||
{ path: SOURCE.path, audioStreamIndex: null },
|
||||
{ startTime: 0, endTime: 5 },
|
||||
'/tmp/window.mkv',
|
||||
);
|
||||
|
||||
assert.equal(args[args.lastIndexOf('-map') + 1], '0:a');
|
||||
});
|
||||
|
||||
test('acquire downloads once and reuses the window for covered ranges', async () => {
|
||||
await withCache({}, {}, async (cache, stub) => {
|
||||
const window = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
|
||||
|
||||
assert.equal(stub.calls.length, 1);
|
||||
assert.equal(argValue(stub.calls[0]!, '-ss'), '9.75');
|
||||
assert.equal(argValue(stub.calls[0]!, '-t'), '5.25');
|
||||
assert.equal(window.startTime, 9.75);
|
||||
assert.equal(window.endTime, 15);
|
||||
assert.equal(window.audioStreamIndex, 2);
|
||||
assert.ok(fs.existsSync(window.path));
|
||||
assert.deepEqual(window.media, {
|
||||
path: window.path,
|
||||
source: 'remote-window',
|
||||
singleResolvedStream: true,
|
||||
absoluteTimestamps: true,
|
||||
});
|
||||
|
||||
assert.equal(await cache.acquire(SOURCE, { startTime: 11, endTime: 15 }), window);
|
||||
assert.equal(await cache.lookup(SOURCE, { startTime: 12, endTime: 12 }), window);
|
||||
assert.equal(
|
||||
await cache.lookup(
|
||||
{ path: SOURCE.path, audioStreamIndex: null },
|
||||
{ startTime: 12, endTime: 13 },
|
||||
),
|
||||
window,
|
||||
);
|
||||
assert.equal(stub.calls.length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('lookup never downloads and misses on other ranges, sources, or audio streams', async () => {
|
||||
await withCache({}, {}, async (cache, stub) => {
|
||||
assert.equal(await cache.lookup(SOURCE, { startTime: 10, endTime: 14 }), null);
|
||||
assert.equal(stub.calls.length, 0);
|
||||
|
||||
await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
|
||||
assert.equal(await cache.lookup(SOURCE, { startTime: 14, endTime: 16 }), null);
|
||||
assert.equal(
|
||||
await cache.lookup(
|
||||
{ path: 'https://other.example/stream', audioStreamIndex: 2 },
|
||||
{
|
||||
startTime: 11,
|
||||
endTime: 12,
|
||||
},
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
await cache.lookup(
|
||||
{ path: SOURCE.path, audioStreamIndex: 3 },
|
||||
{ startTime: 11, endTime: 12 },
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(stub.calls.length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('acquire widens to the union of the old window and replaces the old file', async () => {
|
||||
await withCache({}, {}, async (cache, stub) => {
|
||||
const first = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
|
||||
const second = await cache.acquire(SOURCE, { startTime: 8, endTime: 12 });
|
||||
|
||||
assert.equal(stub.calls.length, 2);
|
||||
assert.equal(argValue(stub.calls[1]!, '-ss'), '7.75');
|
||||
assert.equal(second.startTime, 7.75);
|
||||
assert.equal(second.endTime, 15);
|
||||
assert.notEqual(second.path, first.path);
|
||||
assert.equal(fs.existsSync(first.path), false);
|
||||
assert.ok(fs.existsSync(second.path));
|
||||
assert.equal(cache.currentWindow, second);
|
||||
});
|
||||
});
|
||||
|
||||
test('acquire shares an in-flight download between concurrent callers', async () => {
|
||||
await withCache({ defer: true }, {}, async (cache, stub) => {
|
||||
const first = cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
|
||||
await Promise.resolve();
|
||||
const second = cache.acquire(SOURCE, { startTime: 11, endTime: 13 });
|
||||
const lookup = cache.lookup(SOURCE, { startTime: 12, endTime: 12 });
|
||||
await Promise.resolve();
|
||||
assert.equal(stub.calls.length, 1);
|
||||
|
||||
stub.flush();
|
||||
const [a, b, c] = await Promise.all([first, second, lookup]);
|
||||
assert.equal(a, b);
|
||||
assert.equal(a, c);
|
||||
assert.equal(stub.calls.length, 1);
|
||||
});
|
||||
});
|
||||
|
||||
test('acquire rejects on ffmpeg failure, leaves no file, and can retry', async () => {
|
||||
await withCache({ fail: true }, {}, async (cache, stub) => {
|
||||
await assert.rejects(
|
||||
cache.acquire(SOURCE, { startTime: 10, endTime: 14 }),
|
||||
/FFmpeg media window failed: boom/,
|
||||
);
|
||||
assert.equal(cache.currentWindow, null);
|
||||
assert.equal(await cache.lookup(SOURCE, { startTime: 10, endTime: 14 }), null);
|
||||
|
||||
await assert.rejects(cache.acquire(SOURCE, { startTime: 10, endTime: 14 }));
|
||||
assert.equal(stub.calls.length, 2);
|
||||
});
|
||||
await withCache({ empty: true }, {}, async (cache) => {
|
||||
await assert.rejects(
|
||||
cache.acquire(SOURCE, { startTime: 10, endTime: 14 }),
|
||||
/exited without creating a media window/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('acquire refuses invalid and oversized ranges without spawning ffmpeg', async () => {
|
||||
await withCache({}, {}, async (cache, stub) => {
|
||||
await assert.rejects(cache.acquire(SOURCE, { startTime: 10, endTime: 10 }), /invalid/);
|
||||
await assert.rejects(cache.acquire(SOURCE, { startTime: -1, endTime: 10 }), /invalid/);
|
||||
await assert.rejects(
|
||||
cache.acquire(SOURCE, { startTime: 0, endTime: REMOTE_MEDIA_WINDOW_MAX_SECONDS + 1 }),
|
||||
/too long/,
|
||||
);
|
||||
assert.equal(stub.calls.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
test('the window is deleted after the idle timeout and on cleanup', async () => {
|
||||
await withCache({}, { idleTtlMs: 20 }, async (cache) => {
|
||||
const window = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
assert.equal(cache.currentWindow, null);
|
||||
assert.equal(fs.existsSync(window.path), false);
|
||||
|
||||
const again = await cache.acquire(SOURCE, { startTime: 10, endTime: 14 });
|
||||
cache.cleanup();
|
||||
assert.equal(fs.existsSync(again.path), false);
|
||||
assert.equal(fs.existsSync(path.dirname(again.path)), false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,377 @@
|
||||
import { execFile as nodeExecFile, type ExecFileException } from 'child_process';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { createLogger } from '../../logger';
|
||||
import { normalizeMediaInput, type MediaInput, type MediaInputOptions } from '../../media-input';
|
||||
|
||||
const log = createLogger('media-window');
|
||||
|
||||
export const REMOTE_MEDIA_WINDOW_TIMEOUT_MS = 120_000;
|
||||
export const REMOTE_MEDIA_WINDOW_MAX_SECONDS = 180;
|
||||
const HEAD_SLACK_SECONDS = 0.25;
|
||||
const TAIL_SLACK_SECONDS = 1;
|
||||
const DEFAULT_IDLE_TTL_MS = 10 * 60_000;
|
||||
const COVERAGE_EPSILON_SECONDS = 0.01;
|
||||
|
||||
export interface RemoteMediaWindowSource {
|
||||
path: string;
|
||||
inputOptions?: MediaInputOptions;
|
||||
/** FFmpeg stream index to keep; `null`/undefined keeps every audio stream. */
|
||||
audioStreamIndex?: number | null;
|
||||
}
|
||||
|
||||
export interface RemoteMediaWindowRange {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
}
|
||||
|
||||
export interface RemoteMediaWindow {
|
||||
path: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
sourcePath: string;
|
||||
audioStreamIndex: number | null;
|
||||
/** Input descriptor for FFmpeg reads; timestamps stay absolute so callers keep source times. */
|
||||
media: MediaInput;
|
||||
}
|
||||
|
||||
type WindowExecFile = (
|
||||
file: string,
|
||||
args: readonly string[],
|
||||
options: { timeout: number },
|
||||
callback: (error: ExecFileException | null) => void,
|
||||
) => void;
|
||||
|
||||
export interface RemoteMediaWindowCacheOptions {
|
||||
tempDir?: string;
|
||||
execFile?: WindowExecFile;
|
||||
idleTtlMs?: number;
|
||||
logDebug?: (message: string) => void;
|
||||
}
|
||||
|
||||
interface PendingFetch extends RemoteMediaWindowRange {
|
||||
sourcePath: string;
|
||||
audioStreamIndex: number | null;
|
||||
promise: Promise<RemoteMediaWindow>;
|
||||
}
|
||||
|
||||
export function isRemoteMediaWindowSourcePath(value: string): boolean {
|
||||
return /^https?:\/\//i.test(value.trim());
|
||||
}
|
||||
|
||||
function describeSourceForDebugLog(sourcePath: string): string {
|
||||
try {
|
||||
return `remote:${new URL(sourcePath).hostname.toLowerCase() || 'unknown'}`;
|
||||
} catch {
|
||||
return 'remote:unknown';
|
||||
}
|
||||
}
|
||||
|
||||
function isUsableRange(range: RemoteMediaWindowRange, allowEmpty: boolean): boolean {
|
||||
return (
|
||||
Number.isFinite(range.startTime) &&
|
||||
Number.isFinite(range.endTime) &&
|
||||
range.startTime >= 0 &&
|
||||
(allowEmpty ? range.endTime >= range.startTime : range.endTime > range.startTime)
|
||||
);
|
||||
}
|
||||
|
||||
function audioStreamMatches(
|
||||
windowIndex: number | null,
|
||||
requested: number | null | undefined,
|
||||
): boolean {
|
||||
return requested == null || windowIndex === requested;
|
||||
}
|
||||
|
||||
function covers(
|
||||
candidate: RemoteMediaWindowRange & { sourcePath: string; audioStreamIndex: number | null },
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
): boolean {
|
||||
return (
|
||||
candidate.sourcePath === source.path &&
|
||||
audioStreamMatches(candidate.audioStreamIndex, source.audioStreamIndex) &&
|
||||
candidate.startTime <= range.startTime + COVERAGE_EPSILON_SECONDS &&
|
||||
candidate.endTime >= range.endTime - COVERAGE_EPSILON_SECONDS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream-copies `[startTime, endTime]` of a remote source into a local Matroska file.
|
||||
* `-copyts -start_at_zero` keeps the source timestamps, so later reads seek with the
|
||||
* original times via `-seek_timestamp 1` (see `MediaInput.absoluteTimestamps`).
|
||||
*/
|
||||
export function buildRemoteMediaWindowArgs(
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
outputPath: string,
|
||||
): string[] {
|
||||
const input = normalizeMediaInput({ path: source.path, inputOptions: source.inputOptions });
|
||||
const audioMap =
|
||||
typeof source.audioStreamIndex === 'number' && Number.isInteger(source.audioStreamIndex)
|
||||
? `0:${source.audioStreamIndex}`
|
||||
: '0:a';
|
||||
return [
|
||||
'-hide_banner',
|
||||
'-nostdin',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-ss',
|
||||
String(range.startTime),
|
||||
'-t',
|
||||
String(range.endTime - range.startTime),
|
||||
...input.inputArgs,
|
||||
'-i',
|
||||
input.path,
|
||||
'-map',
|
||||
'0:v:0?',
|
||||
'-map',
|
||||
audioMap,
|
||||
'-c',
|
||||
'copy',
|
||||
'-sn',
|
||||
'-dn',
|
||||
'-copyts',
|
||||
'-start_at_zero',
|
||||
'-f',
|
||||
'matroska',
|
||||
'-y',
|
||||
outputPath,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds one downloaded window of the current remote stream so the timing review,
|
||||
* audio extraction, and screenshot all read the same local bytes instead of each
|
||||
* re-fetching the clip over HTTP. A new window replaces the old one; the file is
|
||||
* deleted after `idleTtlMs` without use, on `clear()`, or on `cleanup()`.
|
||||
*/
|
||||
export class RemoteMediaWindowCache {
|
||||
private readonly tempDir: string;
|
||||
private readonly execFile: WindowExecFile;
|
||||
private readonly idleTtlMs: number;
|
||||
private readonly logDebug: (message: string) => void;
|
||||
private current: RemoteMediaWindow | null = null;
|
||||
private pending: PendingFetch | null = null;
|
||||
private idleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private sequence = 0;
|
||||
|
||||
constructor(options: RemoteMediaWindowCacheOptions = {}) {
|
||||
this.tempDir = options.tempDir ?? path.join(os.tmpdir(), 'subminer-media-windows');
|
||||
this.execFile = options.execFile ?? nodeExecFile;
|
||||
this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
|
||||
this.logDebug = options.logDebug ?? ((message) => log.debug(message));
|
||||
}
|
||||
|
||||
get currentWindow(): RemoteMediaWindow | null {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
/** Returns a ready or in-flight window covering the range; never starts a download. */
|
||||
async lookup(
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
): Promise<RemoteMediaWindow | null> {
|
||||
if (!isUsableRange(range, true)) return null;
|
||||
if (this.current && covers(this.current, source, range)) {
|
||||
this.touch();
|
||||
return this.current;
|
||||
}
|
||||
const pending = this.pending;
|
||||
if (pending && covers(pending, source, range)) {
|
||||
try {
|
||||
const window = await pending.promise;
|
||||
this.touch();
|
||||
return window;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Returns a window covering the range, downloading (and widening) one when needed. */
|
||||
async acquire(
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
): Promise<RemoteMediaWindow> {
|
||||
if (!isUsableRange(range, false)) {
|
||||
throw new Error('Media window range is invalid.');
|
||||
}
|
||||
if (range.endTime - range.startTime > REMOTE_MEDIA_WINDOW_MAX_SECONDS) {
|
||||
throw new Error('Media window range is too long to download.');
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
const hit = await this.lookup(source, range);
|
||||
if (hit) return hit;
|
||||
const pending = this.pending;
|
||||
if (!pending) break;
|
||||
// Another caller is already downloading; wait for it, then re-check coverage.
|
||||
await pending.promise.catch(() => null);
|
||||
}
|
||||
|
||||
return this.fetch(source, this.planFetchRange(source, range));
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cancelIdleTimer();
|
||||
const current = this.current;
|
||||
this.current = null;
|
||||
if (current) this.removeFile(current.path);
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
this.clear();
|
||||
try {
|
||||
fs.rmSync(this.tempDir, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
log.error('Failed to cleanup media window directory:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private planFetchRange(
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
): RemoteMediaWindowRange {
|
||||
let startTime = Math.max(0, range.startTime - HEAD_SLACK_SECONDS);
|
||||
let endTime = range.endTime + TAIL_SLACK_SECONDS;
|
||||
const current = this.current;
|
||||
if (
|
||||
current &&
|
||||
current.sourcePath === source.path &&
|
||||
audioStreamMatches(current.audioStreamIndex, source.audioStreamIndex)
|
||||
) {
|
||||
// Keep what was already downloaded when the review timeline grows in one direction.
|
||||
const unionStart = Math.min(startTime, current.startTime);
|
||||
const unionEnd = Math.max(endTime, current.endTime);
|
||||
if (unionEnd - unionStart <= REMOTE_MEDIA_WINDOW_MAX_SECONDS) {
|
||||
startTime = unionStart;
|
||||
endTime = unionEnd;
|
||||
}
|
||||
}
|
||||
return { startTime, endTime };
|
||||
}
|
||||
|
||||
private fetch(
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
): Promise<RemoteMediaWindow> {
|
||||
fs.mkdirSync(this.tempDir, { recursive: true });
|
||||
this.sequence += 1;
|
||||
const outputPath = path.join(this.tempDir, `window_${Date.now()}_${this.sequence}.mkv`);
|
||||
const audioStreamIndex =
|
||||
typeof source.audioStreamIndex === 'number' ? source.audioStreamIndex : null;
|
||||
const description = describeSourceForDebugLog(source.path);
|
||||
const startedAt = Date.now();
|
||||
this.logDebug(
|
||||
`[media-window] fetch start ${description} start=${range.startTime} end=${range.endTime} audioStream=${audioStreamIndex ?? 'all'}`,
|
||||
);
|
||||
|
||||
const promise = new Promise<RemoteMediaWindow>((resolve, reject) => {
|
||||
this.execFile(
|
||||
'ffmpeg',
|
||||
buildRemoteMediaWindowArgs(source, range, outputPath),
|
||||
{ timeout: REMOTE_MEDIA_WINDOW_TIMEOUT_MS },
|
||||
(error) => {
|
||||
const elapsedMs = Math.max(0, Date.now() - startedAt);
|
||||
const size = error ? 0 : this.fileSize(outputPath);
|
||||
if (error || size === 0) {
|
||||
this.removeFile(outputPath);
|
||||
const reason = error
|
||||
? error.code === 'ENOENT'
|
||||
? 'FFmpeg not found. Install FFmpeg to enable media generation.'
|
||||
: `FFmpeg media window failed: ${error.message}`
|
||||
: 'FFmpeg exited without creating a media window.';
|
||||
this.logDebug(`[media-window] fetch failed ${description} elapsedMs=${elapsedMs}`);
|
||||
reject(new Error(reason));
|
||||
return;
|
||||
}
|
||||
const window: RemoteMediaWindow = {
|
||||
path: outputPath,
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
sourcePath: source.path,
|
||||
audioStreamIndex,
|
||||
media: {
|
||||
path: outputPath,
|
||||
source: 'remote-window',
|
||||
singleResolvedStream: true,
|
||||
absoluteTimestamps: true,
|
||||
},
|
||||
};
|
||||
this.logDebug(
|
||||
`[media-window] fetch complete ${description} elapsedMs=${elapsedMs} bytes=${size}`,
|
||||
);
|
||||
this.replaceCurrent(window);
|
||||
resolve(window);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const pending: PendingFetch = {
|
||||
sourcePath: source.path,
|
||||
audioStreamIndex,
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
promise,
|
||||
};
|
||||
this.pending = pending;
|
||||
promise
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
if (this.pending === pending) this.pending = null;
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
private replaceCurrent(window: RemoteMediaWindow): void {
|
||||
const previous = this.current;
|
||||
this.current = window;
|
||||
if (previous && previous.path !== window.path) this.removeFile(previous.path);
|
||||
this.touch();
|
||||
}
|
||||
|
||||
private touch(): void {
|
||||
this.cancelIdleTimer();
|
||||
if (this.idleTtlMs <= 0 || !this.current) return;
|
||||
const timer = setTimeout(() => {
|
||||
if (this.idleTimer === timer) this.idleTimer = null;
|
||||
this.clear();
|
||||
}, this.idleTtlMs);
|
||||
timer.unref?.();
|
||||
this.idleTimer = timer;
|
||||
}
|
||||
|
||||
private cancelIdleTimer(): void {
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.idleTimer = null;
|
||||
}
|
||||
|
||||
private fileSize(filePath: string): number {
|
||||
try {
|
||||
return fs.statSync(filePath).size;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private removeFile(filePath: string): void {
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
log.debug(`Failed to remove media window ${filePath}:`, (error as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sharedCache: RemoteMediaWindowCache | null = null;
|
||||
|
||||
/** Process-wide cache so the review modal and card media generation share one download. */
|
||||
export function getSharedRemoteMediaWindowCache(): RemoteMediaWindowCache {
|
||||
sharedCache ??= new RemoteMediaWindowCache();
|
||||
return sharedCache;
|
||||
}
|
||||
+44
-12
@@ -235,7 +235,10 @@ import {
|
||||
createCycleSecondarySubModeRuntimeHandler,
|
||||
} from './main/runtime/domains/mpv';
|
||||
import { buildSubtitleTrackDiagnostics } from './main/runtime/mpv-track-diagnostics';
|
||||
import { resolveCanonicalPrimarySubtitle } from './main/runtime/primary-subtitle-text';
|
||||
import {
|
||||
resolveCanonicalPrimarySubtitle,
|
||||
resolvePrimarySubtitle,
|
||||
} from './main/runtime/primary-subtitle-text';
|
||||
import {
|
||||
createBuildCopyCurrentSubtitleMainDepsHandler,
|
||||
createBuildHandleMineSentenceDigitMainDepsHandler,
|
||||
@@ -464,6 +467,8 @@ import { handleCliCommandRuntimeServiceWithContext } from './main/cli-runtime';
|
||||
import { createOverlayModalRuntimeService } from './main/overlay-runtime';
|
||||
import { createOverlayModalInputState } from './main/runtime/overlay-modal-input-state';
|
||||
import { MediaTimingPreviewSession } from './core/services/media-timing-preview';
|
||||
import { getSharedRemoteMediaWindowCache } from './core/services/remote-media-window-cache';
|
||||
import { resolveMediaGenerationInput } from './anki-integration/media-source';
|
||||
import { generateSpeechWaveform } from './core/services/media-timing-waveform';
|
||||
import {
|
||||
collectMediaTimingContextLines,
|
||||
@@ -1827,28 +1832,31 @@ function withCurrentSubtitleTiming(payload: SubtitleData): SubtitleData {
|
||||
}
|
||||
|
||||
function captureCurrentPrimarySubtitleMiningContext(): SubtitleMiningContext | null {
|
||||
const canonical = resolveCanonicalPrimarySubtitle({
|
||||
// Mine what the overlay shows, not raw mpv `sub-text`: the raw text lists every active
|
||||
// event, so a finished caption row lingering beside a fresh line would end up on the
|
||||
// card. The parsed view also carries the cue's own timings for the clip range.
|
||||
const resolved = resolvePrimarySubtitle({
|
||||
liveText: appState.mpvClient?.currentSubText ?? '',
|
||||
currentTimeSec: Number(appState.mpvClient?.currentTimePos),
|
||||
cues: appState.activeParsedSubtitleCues,
|
||||
});
|
||||
// Same validity bar as the live capture path: an unusable canonical span must fall
|
||||
// Same validity bar as the live capture path: an unusable resolved span must fall
|
||||
// back rather than hand mining an empty line or an inverted range.
|
||||
const canonicalText = canonical?.text.trim();
|
||||
const resolvedText = resolved?.text.replace(/\n{2,}/g, '\n').trim();
|
||||
if (
|
||||
!canonical ||
|
||||
!canonicalText ||
|
||||
!Number.isFinite(canonical.startTime) ||
|
||||
!Number.isFinite(canonical.endTime) ||
|
||||
canonical.endTime <= canonical.startTime
|
||||
!resolved ||
|
||||
!resolvedText ||
|
||||
!Number.isFinite(resolved.startTime) ||
|
||||
!Number.isFinite(resolved.endTime) ||
|
||||
resolved.endTime <= resolved.startTime
|
||||
) {
|
||||
return captureLiveSubtitleMiningContext(appState.mpvClient);
|
||||
}
|
||||
return {
|
||||
source: 'overlay',
|
||||
text: canonicalText,
|
||||
startTime: canonical.startTime,
|
||||
endTime: canonical.endTime,
|
||||
text: resolvedText,
|
||||
startTime: resolved.startTime,
|
||||
endTime: resolved.endTime,
|
||||
capturedAtMs: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -2896,6 +2904,21 @@ const mediaTimingReviewRuntime = createMediaTimingReviewRuntime({
|
||||
configService.getConfig().mpv.executablePath || process.env.SUBMINER_MPV_PATH?.trim() || '',
|
||||
createPreviewSession: () => new MediaTimingPreviewSession(),
|
||||
generateWaveform: (options) => generateSpeechWaveform(options),
|
||||
resolveMediaSource: async () => {
|
||||
const resolved = await resolveMediaGenerationInput(appState.mpvClient, 'audio', {
|
||||
getCachedMediaPath: (currentVideoPath, kind) =>
|
||||
getCachedYoutubeMediaPathForCurrentPlayback(currentVideoPath, kind),
|
||||
remoteCacheMode: shouldRequireYoutubeMediaCacheForCurrentPlayback() ? 'required' : 'optional',
|
||||
});
|
||||
return resolved
|
||||
? {
|
||||
path: resolved.path,
|
||||
...(resolved.inputOptions ? { inputOptions: resolved.inputOptions } : {}),
|
||||
singleResolvedStream: resolved.singleResolvedStream,
|
||||
}
|
||||
: null;
|
||||
},
|
||||
acquireMediaWindow: (source, range) => getSharedRemoteMediaWindowCache().acquire(source, range),
|
||||
getSubtitleContextLines: (range) =>
|
||||
collectMediaTimingContextLines({
|
||||
cues: appState.activeParsedSubtitleCues,
|
||||
@@ -2904,6 +2927,14 @@ const mediaTimingReviewRuntime = createMediaTimingReviewRuntime({
|
||||
endTime: range.endTime,
|
||||
}),
|
||||
openModal: (payload) => openMediaTimingReviewModal(createOverlayHostedModalOpenDeps(), payload),
|
||||
onPreviewEnded: (reviewId) => {
|
||||
// The review may live in either overlay window; the renderer ignores foreign review ids.
|
||||
for (const window of [overlayManager.getMainWindow(), overlayManager.getModalWindow()]) {
|
||||
if (window && !window.isDestroyed()) {
|
||||
window.webContents.send(IPC_CHANNELS.event.mediaTimingReviewPreviewEnded, reviewId);
|
||||
}
|
||||
}
|
||||
},
|
||||
showStatus: (message) =>
|
||||
overlayNotificationsRuntime.showConfiguredStatusNotification(message, { variant: 'warning' }),
|
||||
});
|
||||
@@ -3973,6 +4004,7 @@ const {
|
||||
cleanupInternalSubtitleTrackCache: () => cachedInternalSubtitleTrackExtractor.clear(),
|
||||
cleanupYoutubeSubtitleTempDirs: () => youtubeFlowRuntime.cleanupSubtitleTempDirs(),
|
||||
cleanupYoutubeMediaCache: () => youtubeMediaCache.cleanup(),
|
||||
cleanupRemoteMediaWindows: () => getSharedRemoteMediaWindowCache().cleanup(),
|
||||
cleanupJellyfinSubtitleCache: () => cleanupJellyfinSubtitleCache(),
|
||||
stopDiscordPresenceService: () => {
|
||||
void appState.discordPresenceService?.stop();
|
||||
|
||||
@@ -46,12 +46,13 @@ test('on will quit cleanup handler runs all cleanup steps', () => {
|
||||
cleanupInternalSubtitleTrackCache: () => calls.push('cleanup-internal-subtitles'),
|
||||
cleanupYoutubeSubtitleTempDirs: () => calls.push('cleanup-youtube-subtitles'),
|
||||
cleanupYoutubeMediaCache: () => calls.push('cleanup-youtube-media'),
|
||||
cleanupRemoteMediaWindows: () => calls.push('cleanup-remote-media-windows'),
|
||||
cleanupJellyfinSubtitleCache: () => calls.push('cleanup-jellyfin-subtitles'),
|
||||
stopDiscordPresenceService: () => calls.push('stop-discord-presence'),
|
||||
});
|
||||
|
||||
cleanup();
|
||||
assert.equal(calls.length, 35);
|
||||
assert.equal(calls.length, 36);
|
||||
assert.equal(calls[0], 'destroy-tray');
|
||||
assert.equal(calls[calls.length - 1], 'stop-discord-presence');
|
||||
assert.ok(calls.includes('cleanup-jellyfin-subtitles'));
|
||||
@@ -60,6 +61,7 @@ test('on will quit cleanup handler runs all cleanup steps', () => {
|
||||
assert.ok(calls.includes('clear-linux-mpv-fullscreen-overlay-refresh-timeouts'));
|
||||
assert.ok(calls.includes('cleanup-youtube-subtitles'));
|
||||
assert.ok(calls.includes('cleanup-youtube-media'));
|
||||
assert.ok(calls.includes('cleanup-remote-media-windows'));
|
||||
assert.ok(calls.indexOf('flush-mpv-log') < calls.indexOf('destroy-socket'));
|
||||
});
|
||||
|
||||
@@ -102,6 +104,7 @@ test('on will quit cleanup handler cleans jellyfin subtitle cache when stopping
|
||||
cleanupInternalSubtitleTrackCache: () => calls.push('cleanup-internal-subtitles'),
|
||||
cleanupYoutubeSubtitleTempDirs: () => calls.push('cleanup-youtube-subtitles'),
|
||||
cleanupYoutubeMediaCache: () => calls.push('cleanup-youtube-media'),
|
||||
cleanupRemoteMediaWindows: () => calls.push('cleanup-remote-media-windows'),
|
||||
cleanupJellyfinSubtitleCache: () => calls.push('cleanup-jellyfin-subtitles'),
|
||||
stopDiscordPresenceService: () => calls.push('stop-discord-presence'),
|
||||
});
|
||||
|
||||
@@ -32,6 +32,7 @@ export function createOnWillQuitCleanupHandler(deps: {
|
||||
cleanupInternalSubtitleTrackCache: () => void;
|
||||
cleanupYoutubeSubtitleTempDirs: () => void;
|
||||
cleanupYoutubeMediaCache: () => void;
|
||||
cleanupRemoteMediaWindows: () => void;
|
||||
cleanupJellyfinSubtitleCache: () => void;
|
||||
stopDiscordPresenceService: () => void;
|
||||
}) {
|
||||
@@ -76,6 +77,7 @@ export function createOnWillQuitCleanupHandler(deps: {
|
||||
}
|
||||
deps.cleanupYoutubeSubtitleTempDirs();
|
||||
deps.cleanupYoutubeMediaCache();
|
||||
deps.cleanupRemoteMediaWindows();
|
||||
deps.stopDiscordPresenceService();
|
||||
return Promise.resolve(stopSyncAutoScheduler);
|
||||
};
|
||||
|
||||
@@ -75,6 +75,7 @@ test('cleanup deps builder returns handlers that guard optional runtime objects'
|
||||
cleanupInternalSubtitleTrackCache: () => calls.push('cleanup-internal-subtitles'),
|
||||
cleanupYoutubeSubtitleTempDirs: () => calls.push('cleanup-youtube-subtitles'),
|
||||
cleanupYoutubeMediaCache: () => calls.push('cleanup-youtube-media'),
|
||||
cleanupRemoteMediaWindows: () => calls.push('cleanup-remote-media-windows'),
|
||||
cleanupJellyfinSubtitleCache: () => calls.push('cleanup-jellyfin-subtitles'),
|
||||
stopDiscordPresenceService: () => calls.push('stop-discord-presence'),
|
||||
});
|
||||
@@ -157,6 +158,7 @@ test('cleanup deps builder skips destroyed yomitan window', () => {
|
||||
cleanupInternalSubtitleTrackCache: () => {},
|
||||
cleanupYoutubeSubtitleTempDirs: () => {},
|
||||
cleanupYoutubeMediaCache: () => {},
|
||||
cleanupRemoteMediaWindows: () => {},
|
||||
cleanupJellyfinSubtitleCache: () => {},
|
||||
stopDiscordPresenceService: () => {},
|
||||
});
|
||||
@@ -210,6 +212,7 @@ test('cleanup deps builder skips global shortcut cleanup before app ready', () =
|
||||
cleanupInternalSubtitleTrackCache: () => {},
|
||||
cleanupYoutubeSubtitleTempDirs: () => {},
|
||||
cleanupYoutubeMediaCache: () => {},
|
||||
cleanupRemoteMediaWindows: () => {},
|
||||
cleanupJellyfinSubtitleCache: () => {},
|
||||
stopDiscordPresenceService: () => {},
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
|
||||
cleanupInternalSubtitleTrackCache: () => void;
|
||||
cleanupYoutubeSubtitleTempDirs: () => void;
|
||||
cleanupYoutubeMediaCache: () => void;
|
||||
cleanupRemoteMediaWindows: () => void;
|
||||
cleanupJellyfinSubtitleCache: () => void;
|
||||
stopDiscordPresenceService: () => void;
|
||||
}) {
|
||||
@@ -148,6 +149,7 @@ export function createBuildOnWillQuitCleanupDepsHandler(deps: {
|
||||
cleanupInternalSubtitleTrackCache: () => deps.cleanupInternalSubtitleTrackCache(),
|
||||
cleanupYoutubeSubtitleTempDirs: () => deps.cleanupYoutubeSubtitleTempDirs(),
|
||||
cleanupYoutubeMediaCache: () => deps.cleanupYoutubeMediaCache(),
|
||||
cleanupRemoteMediaWindows: () => deps.cleanupRemoteMediaWindows(),
|
||||
cleanupJellyfinSubtitleCache: () => deps.cleanupJellyfinSubtitleCache(),
|
||||
stopDiscordPresenceService: () => deps.stopDiscordPresenceService(),
|
||||
});
|
||||
|
||||
@@ -52,6 +52,7 @@ test('composeStartupLifecycleHandlers returns callable startup lifecycle handler
|
||||
cleanupInternalSubtitleTrackCache: () => {},
|
||||
cleanupYoutubeSubtitleTempDirs: () => {},
|
||||
cleanupYoutubeMediaCache: () => {},
|
||||
cleanupRemoteMediaWindows: () => {},
|
||||
cleanupJellyfinSubtitleCache: () => {},
|
||||
stopDiscordPresenceService: () => {},
|
||||
},
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, test } from 'node:test';
|
||||
import type { MediaTimingReviewOpenPayload } from '../../types/anki';
|
||||
import type { SpeechWaveformOptions } from '../../core/services/media-timing-waveform';
|
||||
import type {
|
||||
RemoteMediaWindow,
|
||||
RemoteMediaWindowRange,
|
||||
RemoteMediaWindowSource,
|
||||
} from '../../core/services/remote-media-window-cache';
|
||||
import type { MediaTimingPreviewSession } from '../../core/services/media-timing-preview';
|
||||
|
||||
type MediaTimingPreviewSessionLike = Pick<MediaTimingPreviewSession, 'start'>;
|
||||
import {
|
||||
buildMediaTimingReviewPayload,
|
||||
collectMediaTimingContextLines,
|
||||
@@ -93,6 +102,7 @@ async function startActiveMediaTimingReview(
|
||||
previewCalls.push([startTime, endTime]);
|
||||
},
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async (payload) => {
|
||||
@@ -136,6 +146,7 @@ test('media timing review pauses playback, resolves exact timing, and restores p
|
||||
previewCalls.push([startTime, endTime]);
|
||||
},
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async (payload) => {
|
||||
@@ -177,12 +188,7 @@ test('media timing review pauses playback, resolves exact timing, and restores p
|
||||
});
|
||||
|
||||
test('media timing review analyzes the visible range on the selected audio stream', async () => {
|
||||
const waveformCalls: Array<{
|
||||
mediaPath: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
audioStreamIndex?: number;
|
||||
}> = [];
|
||||
const waveformCalls: SpeechWaveformOptions[] = [];
|
||||
let runtime: ReturnType<typeof createMediaTimingReviewRuntime>;
|
||||
runtime = createMediaTimingReviewRuntime({
|
||||
getMpvClient: () => ({
|
||||
@@ -202,6 +208,7 @@ test('media timing review analyzes the visible range on the selected audio strea
|
||||
start: async () => undefined,
|
||||
play: async () => undefined,
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async (payload) => {
|
||||
@@ -239,6 +246,302 @@ test('media timing review analyzes the visible range on the selected audio strea
|
||||
]);
|
||||
});
|
||||
|
||||
const REMOTE_STREAM_URL = 'https://jellyfin.example/Videos/abc/stream?static=true';
|
||||
|
||||
function createWindowStub(options: { fail?: boolean } = {}) {
|
||||
const calls: Array<{ source: RemoteMediaWindowSource; range: RemoteMediaWindowRange }> = [];
|
||||
const acquireMediaWindow = async (
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
): Promise<RemoteMediaWindow> => {
|
||||
calls.push({ source, range });
|
||||
if (options.fail) throw new Error('offline');
|
||||
const windowPath = `/tmp/window-${range.startTime}-${range.endTime}.mkv`;
|
||||
return {
|
||||
path: windowPath,
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
sourcePath: source.path,
|
||||
audioStreamIndex: source.audioStreamIndex ?? null,
|
||||
media: {
|
||||
path: windowPath,
|
||||
source: 'remote-window',
|
||||
singleResolvedStream: true,
|
||||
absoluteTimestamps: true,
|
||||
},
|
||||
};
|
||||
};
|
||||
return { calls, acquireMediaWindow };
|
||||
}
|
||||
|
||||
function createRemoteReviewRuntime(options: {
|
||||
windowStub: ReturnType<typeof createWindowStub>;
|
||||
waveformCalls: SpeechWaveformOptions[];
|
||||
previewStarts: Array<Parameters<MediaTimingPreviewSessionLike['start']>[0]>;
|
||||
previewPlays: Array<[string, number, number]>;
|
||||
disposed: string[];
|
||||
openModal: (
|
||||
runtime: ReturnType<typeof createMediaTimingReviewRuntime>,
|
||||
payload: MediaTimingReviewOpenPayload,
|
||||
) => Promise<void>;
|
||||
}) {
|
||||
let runtime!: ReturnType<typeof createMediaTimingReviewRuntime>;
|
||||
runtime = createMediaTimingReviewRuntime({
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentVideoPath: REMOTE_STREAM_URL,
|
||||
currentAudioStreamIndex: 2,
|
||||
requestProperty: async (name) =>
|
||||
({ pause: true, duration: 100, aid: 3, volume: 60 })[
|
||||
name as 'pause' | 'duration' | 'aid' | 'volume'
|
||||
] ?? null,
|
||||
send: () => undefined,
|
||||
}),
|
||||
getCurrentMediaPath: () => REMOTE_STREAM_URL,
|
||||
getMpvExecutablePath: () => 'mpv',
|
||||
resolveMediaSource: async () => ({
|
||||
path: REMOTE_STREAM_URL,
|
||||
inputOptions: { reconnect: true },
|
||||
}),
|
||||
acquireMediaWindow: options.windowStub.acquireMediaWindow,
|
||||
generateWaveform: async (waveformOptions) => {
|
||||
options.waveformCalls.push(waveformOptions);
|
||||
return [0.1, 0.8, 0.2];
|
||||
},
|
||||
createPreviewSession: () => {
|
||||
let mediaPath = '';
|
||||
return {
|
||||
start: async (startOptions) => {
|
||||
mediaPath = startOptions.mediaPath;
|
||||
options.previewStarts.push(startOptions);
|
||||
},
|
||||
play: async (startTime, endTime) => {
|
||||
options.previewPlays.push([mediaPath, startTime, endTime]);
|
||||
},
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => {
|
||||
options.disposed.push(mediaPath);
|
||||
},
|
||||
};
|
||||
},
|
||||
openModal: async (payload) => {
|
||||
await options.openModal(runtime, payload);
|
||||
return true;
|
||||
},
|
||||
showStatus: () => undefined,
|
||||
});
|
||||
return runtime;
|
||||
}
|
||||
|
||||
test('media timing review downloads one window of a remote stream for the waveform and preview', async () => {
|
||||
const windowStub = createWindowStub();
|
||||
const waveformCalls: SpeechWaveformOptions[] = [];
|
||||
const previewStarts: Array<Parameters<MediaTimingPreviewSessionLike['start']>[0]> = [];
|
||||
const previewPlays: Array<[string, number, number]> = [];
|
||||
const disposed: string[] = [];
|
||||
const runtime = createRemoteReviewRuntime({
|
||||
windowStub,
|
||||
waveformCalls,
|
||||
previewStarts,
|
||||
previewPlays,
|
||||
disposed,
|
||||
openModal: async (active, payload) => {
|
||||
const waveform = await active.getWaveform({
|
||||
reviewId: payload.reviewId,
|
||||
startTime: payload.timelineStartTime,
|
||||
endTime: payload.timelineEndTime,
|
||||
});
|
||||
assert.deepEqual(waveform, { ok: true, peaks: [0.1, 0.8, 0.2] });
|
||||
assert.deepEqual(
|
||||
await active.previewRange({ reviewId: payload.reviewId, startTime: 9.5, endTime: 12.5 }),
|
||||
{ ok: true },
|
||||
);
|
||||
active.resolveReview({
|
||||
reviewId: payload.reviewId,
|
||||
decision: { action: 'confirm', startTime: 9.5, endTime: 12.5 },
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const decision = await runtime.requestReview({
|
||||
kind: 'word',
|
||||
text: '字幕',
|
||||
startTime: 10,
|
||||
endTime: 12,
|
||||
audioPadding: 0.5,
|
||||
maxMediaDuration: 30,
|
||||
});
|
||||
|
||||
assert.deepEqual(decision, { action: 'confirm', startTime: 9.5, endTime: 12.5 });
|
||||
assert.deepEqual(windowStub.calls, [
|
||||
{
|
||||
source: { path: REMOTE_STREAM_URL, inputOptions: { reconnect: true }, audioStreamIndex: 2 },
|
||||
range: { startTime: 7.5, endTime: 14.5 },
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(waveformCalls, [
|
||||
{
|
||||
mediaPath: {
|
||||
path: '/tmp/window-7.5-14.5.mkv',
|
||||
source: 'remote-window',
|
||||
singleResolvedStream: true,
|
||||
absoluteTimestamps: true,
|
||||
},
|
||||
startTime: 7.5,
|
||||
endTime: 14.5,
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(previewStarts, [
|
||||
{
|
||||
mediaPath: '/tmp/window-7.5-14.5.mkv',
|
||||
executablePath: 'mpv',
|
||||
volume: 60,
|
||||
absoluteTimestamps: true,
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(previewPlays, [['/tmp/window-7.5-14.5.mkv', 9.5, 12.5]]);
|
||||
assert.deepEqual(disposed, ['/tmp/window-7.5-14.5.mkv']);
|
||||
});
|
||||
|
||||
test('media timing review restarts the preview on a wider window when the timeline grows', async () => {
|
||||
const windowStub = createWindowStub();
|
||||
const waveformCalls: SpeechWaveformOptions[] = [];
|
||||
const previewStarts: Array<Parameters<MediaTimingPreviewSessionLike['start']>[0]> = [];
|
||||
const previewPlays: Array<[string, number, number]> = [];
|
||||
const disposed: string[] = [];
|
||||
const runtime = createRemoteReviewRuntime({
|
||||
windowStub,
|
||||
waveformCalls,
|
||||
previewStarts,
|
||||
previewPlays,
|
||||
disposed,
|
||||
openModal: async (active, payload) => {
|
||||
await active.previewRange({ reviewId: payload.reviewId, startTime: 9.5, endTime: 12.5 });
|
||||
// The user revealed two more seconds before the clip.
|
||||
await active.getWaveform({ reviewId: payload.reviewId, startTime: 5.5, endTime: 14.5 });
|
||||
await active.previewRange({ reviewId: payload.reviewId, startTime: 6, endTime: 12.5 });
|
||||
active.resolveReview({ reviewId: payload.reviewId, decision: { action: 'use-original' } });
|
||||
},
|
||||
});
|
||||
|
||||
await runtime.requestReview({
|
||||
kind: 'sentence',
|
||||
text: '字幕',
|
||||
startTime: 10,
|
||||
endTime: 12,
|
||||
audioPadding: 0.5,
|
||||
maxMediaDuration: 30,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
windowStub.calls.map((call) => call.range),
|
||||
[
|
||||
{ startTime: 7.5, endTime: 14.5 },
|
||||
{ startTime: 5.5, endTime: 14.5 },
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
previewStarts.map((start) => start.mediaPath),
|
||||
['/tmp/window-7.5-14.5.mkv', '/tmp/window-5.5-14.5.mkv'],
|
||||
);
|
||||
assert.deepEqual(previewPlays, [
|
||||
['/tmp/window-7.5-14.5.mkv', 9.5, 12.5],
|
||||
['/tmp/window-5.5-14.5.mkv', 6, 12.5],
|
||||
]);
|
||||
assert.deepEqual(disposed, ['/tmp/window-7.5-14.5.mkv', '/tmp/window-5.5-14.5.mkv']);
|
||||
assert.equal(waveformCalls[0]?.startTime, 5.5);
|
||||
});
|
||||
|
||||
test('media timing review falls back to the remote stream after one failed window download', async () => {
|
||||
const windowStub = createWindowStub({ fail: true });
|
||||
const waveformCalls: SpeechWaveformOptions[] = [];
|
||||
const previewStarts: Array<Parameters<MediaTimingPreviewSessionLike['start']>[0]> = [];
|
||||
const previewPlays: Array<[string, number, number]> = [];
|
||||
const disposed: string[] = [];
|
||||
const runtime = createRemoteReviewRuntime({
|
||||
windowStub,
|
||||
waveformCalls,
|
||||
previewStarts,
|
||||
previewPlays,
|
||||
disposed,
|
||||
openModal: async (active, payload) => {
|
||||
await active.getWaveform({
|
||||
reviewId: payload.reviewId,
|
||||
startTime: payload.timelineStartTime,
|
||||
endTime: payload.timelineEndTime,
|
||||
});
|
||||
await active.previewRange({ reviewId: payload.reviewId, startTime: 9.5, endTime: 12.5 });
|
||||
active.resolveReview({ reviewId: payload.reviewId, decision: { action: 'use-original' } });
|
||||
},
|
||||
});
|
||||
|
||||
await runtime.requestReview({
|
||||
kind: 'word',
|
||||
text: '字幕',
|
||||
startTime: 10,
|
||||
endTime: 12,
|
||||
audioPadding: 0.5,
|
||||
maxMediaDuration: 30,
|
||||
});
|
||||
|
||||
assert.equal(windowStub.calls.length, 1);
|
||||
assert.deepEqual(waveformCalls, [
|
||||
{
|
||||
mediaPath: { path: REMOTE_STREAM_URL, inputOptions: { reconnect: true } },
|
||||
startTime: 7.5,
|
||||
endTime: 14.5,
|
||||
audioStreamIndex: 2,
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(previewStarts, [
|
||||
{ mediaPath: REMOTE_STREAM_URL, executablePath: 'mpv', volume: 60, audioTrackId: 3 },
|
||||
]);
|
||||
assert.deepEqual(previewPlays, [[REMOTE_STREAM_URL, 9.5, 12.5]]);
|
||||
});
|
||||
|
||||
test('media timing review never downloads windows for local media', async () => {
|
||||
const windowStub = createWindowStub();
|
||||
let runtime!: ReturnType<typeof createMediaTimingReviewRuntime>;
|
||||
runtime = createMediaTimingReviewRuntime({
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentVideoPath: '/video/show.mkv',
|
||||
requestProperty: async (name) => (name === 'duration' ? 100 : name === 'pause' ? true : null),
|
||||
send: () => undefined,
|
||||
}),
|
||||
getCurrentMediaPath: () => '/video/show.mkv',
|
||||
getMpvExecutablePath: () => 'mpv',
|
||||
resolveMediaSource: async () => ({ path: '/video/show.mkv' }),
|
||||
acquireMediaWindow: windowStub.acquireMediaWindow,
|
||||
generateWaveform: async () => [0.1, 0.8, 0.2],
|
||||
createPreviewSession: () => ({
|
||||
start: async () => undefined,
|
||||
play: async () => undefined,
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async (payload) => {
|
||||
await runtime.getWaveform({ reviewId: payload.reviewId, startTime: 7.5, endTime: 14.5 });
|
||||
runtime.resolveReview({ reviewId: payload.reviewId, decision: { action: 'use-original' } });
|
||||
return true;
|
||||
},
|
||||
showStatus: () => undefined,
|
||||
});
|
||||
|
||||
await runtime.requestReview({
|
||||
kind: 'sentence',
|
||||
text: '字幕',
|
||||
startTime: 10,
|
||||
endTime: 12,
|
||||
audioPadding: 0.5,
|
||||
maxMediaDuration: 30,
|
||||
});
|
||||
|
||||
assert.equal(windowStub.calls.length, 0);
|
||||
});
|
||||
|
||||
test('media timing review rejects stale and out-of-range actions before allowing discard', async () => {
|
||||
const { runtime, payload, pendingDecision, previewCalls } = await startActiveMediaTimingReview({
|
||||
maxMediaDuration: 3,
|
||||
@@ -346,6 +649,7 @@ test('media timing review does not resume playback when the prior state is unava
|
||||
},
|
||||
play: async () => undefined,
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async (payload) => {
|
||||
@@ -384,11 +688,17 @@ test('media timing review restores playback when setup fails after pausing', asy
|
||||
send: ({ command }) => commands.push(command),
|
||||
}),
|
||||
getCurrentMediaPath: () => '/video/show.mkv',
|
||||
getMpvExecutablePath: () => 'mpv',
|
||||
generateWaveform: async () => [],
|
||||
createPreviewSession: () => {
|
||||
getMpvExecutablePath: () => {
|
||||
throw new Error('preview setup failed');
|
||||
},
|
||||
generateWaveform: async () => [],
|
||||
createPreviewSession: () => ({
|
||||
start: async () => undefined,
|
||||
play: async () => undefined,
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async () => true,
|
||||
showStatus: () => undefined,
|
||||
});
|
||||
@@ -426,6 +736,7 @@ test('disposing an open review settles it with original timing and restores play
|
||||
start: async () => undefined,
|
||||
play: async () => undefined,
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: () => undefined,
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async () => true,
|
||||
@@ -449,3 +760,64 @@ test('disposing an open review settles it with original timing and restores play
|
||||
['set_property', 'pause', 'no'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('media timing review forwards the hidden player finishing a preview to the modal', async () => {
|
||||
const endedReviewIds: string[] = [];
|
||||
const playback: { ended?: () => void } = {};
|
||||
let publishPayload!: (payload: MediaTimingReviewOpenPayload) => void;
|
||||
const openedPayload = new Promise<MediaTimingReviewOpenPayload>((resolve) => {
|
||||
publishPayload = resolve;
|
||||
});
|
||||
const runtime = createMediaTimingReviewRuntime({
|
||||
getMpvClient: () => ({
|
||||
connected: true,
|
||||
currentVideoPath: '/video/show.mkv',
|
||||
requestProperty: async (name) => (name === 'duration' ? 100 : null),
|
||||
send: () => undefined,
|
||||
}),
|
||||
getCurrentMediaPath: () => '/video/show.mkv',
|
||||
getMpvExecutablePath: () => 'mpv',
|
||||
generateWaveform: async () => [],
|
||||
createPreviewSession: () => ({
|
||||
start: async () => undefined,
|
||||
play: async () => undefined,
|
||||
stop: async () => undefined,
|
||||
onPlaybackEnded: (listener) => {
|
||||
playback.ended = listener;
|
||||
},
|
||||
dispose: () => undefined,
|
||||
}),
|
||||
openModal: async (payload) => {
|
||||
publishPayload(payload);
|
||||
return true;
|
||||
},
|
||||
onPreviewEnded: (reviewId) => {
|
||||
endedReviewIds.push(reviewId);
|
||||
},
|
||||
showStatus: () => undefined,
|
||||
});
|
||||
const pendingDecision = runtime.requestReview({
|
||||
kind: 'sentence',
|
||||
text: '字幕',
|
||||
startTime: 10,
|
||||
endTime: 12,
|
||||
audioPadding: 0,
|
||||
maxMediaDuration: 30,
|
||||
});
|
||||
const payload = await openedPayload;
|
||||
|
||||
assert.deepEqual(
|
||||
await runtime.previewRange({ reviewId: payload.reviewId, startTime: 10, endTime: 12 }),
|
||||
{
|
||||
ok: true,
|
||||
},
|
||||
);
|
||||
assert.ok(playback.ended);
|
||||
playback.ended();
|
||||
assert.deepEqual(endedReviewIds, [payload.reviewId]);
|
||||
|
||||
runtime.resolveReview({ reviewId: payload.reviewId, decision: { action: 'use-original' } });
|
||||
await pendingDecision;
|
||||
playback.ended();
|
||||
assert.deepEqual(endedReviewIds, [payload.reviewId]);
|
||||
});
|
||||
|
||||
@@ -11,6 +11,13 @@ import type {
|
||||
MediaTimingReviewWaveformResult,
|
||||
} from '../../types/anki';
|
||||
import type { SpeechWaveformOptions } from '../../core/services/media-timing-waveform';
|
||||
import {
|
||||
isRemoteMediaWindowSourcePath,
|
||||
type RemoteMediaWindow,
|
||||
type RemoteMediaWindowRange,
|
||||
type RemoteMediaWindowSource,
|
||||
} from '../../core/services/remote-media-window-cache';
|
||||
import type { MediaInput, MediaInputOptions } from '../../media-input';
|
||||
|
||||
const INITIAL_TIMELINE_MARGIN_SECONDS = 2;
|
||||
const REVIEW_DECISION_TIMEOUT_MS = 5 * 60_000;
|
||||
@@ -31,19 +38,38 @@ interface PreviewSession {
|
||||
executablePath?: string;
|
||||
audioTrackId?: number;
|
||||
volume?: number;
|
||||
absoluteTimestamps?: boolean;
|
||||
}): Promise<void>;
|
||||
play(startTime: number, endTime: number): Promise<void>;
|
||||
stop(): Promise<void>;
|
||||
/** Fires when the player reaches the end of the clip started by play(). */
|
||||
onPlaybackEnded(listener: () => void): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
interface ReviewMediaSource {
|
||||
path: string;
|
||||
inputOptions?: MediaInputOptions;
|
||||
singleResolvedStream?: boolean;
|
||||
}
|
||||
|
||||
interface ActiveReview {
|
||||
payload: MediaTimingReviewOpenPayload;
|
||||
/** What the hidden mpv preview plays when no cached window is available. */
|
||||
mediaPath: string;
|
||||
/** What the waveform reads when no cached window is available. */
|
||||
waveformMedia: MediaInput;
|
||||
audioStreamIndex?: number;
|
||||
/** Remote source to download windows of; null for local media or without a cache. */
|
||||
windowSource: RemoteMediaWindowSource | null;
|
||||
/** Latest window returned for this review; reused while it still covers the request. */
|
||||
window: RemoteMediaWindow | null;
|
||||
windowRequest: (RemoteMediaWindowRange & { promise: Promise<RemoteMediaWindow | null> }) | null;
|
||||
windowFailed: boolean;
|
||||
previewOptions: { executablePath?: string; audioTrackId?: number; volume?: number };
|
||||
preview: { path: string; session: Promise<PreviewSession> } | null;
|
||||
mpvClient: ReviewMpvClient;
|
||||
restorePlayback: boolean;
|
||||
preview: Promise<PreviewSession>;
|
||||
resolve: (decision: MediaTimingReviewDecision) => void;
|
||||
}
|
||||
|
||||
@@ -53,12 +79,21 @@ export interface MediaTimingReviewRuntimeDeps {
|
||||
getMpvExecutablePath: () => string;
|
||||
createPreviewSession: () => PreviewSession;
|
||||
generateWaveform: (options: SpeechWaveformOptions) => Promise<number[]>;
|
||||
/** Resolves the FFmpeg-readable stream URL and headers behind the current media path. */
|
||||
resolveMediaSource?: () => Promise<ReviewMediaSource | null>;
|
||||
/** Downloads (or reuses) a local window of a remote source covering the range. */
|
||||
acquireMediaWindow?: (
|
||||
source: RemoteMediaWindowSource,
|
||||
range: RemoteMediaWindowRange,
|
||||
) => Promise<RemoteMediaWindow>;
|
||||
getSubtitleContextLines?: (range: { startTime: number; endTime: number }) => {
|
||||
previous: MediaTimingReviewContextLine[];
|
||||
next: MediaTimingReviewContextLine[];
|
||||
};
|
||||
decisionTimeoutMs?: number;
|
||||
openModal: (payload: MediaTimingReviewOpenPayload) => Promise<boolean>;
|
||||
/** Tells the modal that the hidden player finished the previewed clip. */
|
||||
onPreviewEnded?: (reviewId: string) => void;
|
||||
showStatus: (message: string) => void;
|
||||
}
|
||||
|
||||
@@ -199,6 +234,89 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
}
|
||||
}
|
||||
|
||||
function ensureWindow(
|
||||
review: ActiveReview,
|
||||
range: RemoteMediaWindowRange,
|
||||
): Promise<RemoteMediaWindow | null> {
|
||||
const { windowSource } = review;
|
||||
if (!windowSource || review.windowFailed || !deps.acquireMediaWindow) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const coversRange = (candidate: RemoteMediaWindowRange): boolean =>
|
||||
candidate.startTime <= range.startTime && candidate.endTime >= range.endTime;
|
||||
if (review.window && coversRange(review.window)) return Promise.resolve(review.window);
|
||||
const inFlight = review.windowRequest;
|
||||
if (inFlight && coversRange(inFlight)) return inFlight.promise;
|
||||
|
||||
const request = {
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
promise: Promise.resolve<RemoteMediaWindow | null>(null),
|
||||
};
|
||||
request.promise = deps
|
||||
.acquireMediaWindow(windowSource, { startTime: range.startTime, endTime: range.endTime })
|
||||
.then((window) => {
|
||||
review.window = window;
|
||||
return window;
|
||||
})
|
||||
.catch(() => {
|
||||
// Fall back to the remote source for the rest of this review instead of retrying.
|
||||
review.windowFailed = true;
|
||||
return null;
|
||||
})
|
||||
.finally(() => {
|
||||
if (review.windowRequest === request) review.windowRequest = null;
|
||||
});
|
||||
review.windowRequest = request;
|
||||
return request.promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the preview player for the range, restarting it when the range needs a
|
||||
* different file (the first cached window, or a wider one after the timeline grew).
|
||||
*/
|
||||
async function previewFor(
|
||||
review: ActiveReview,
|
||||
range: RemoteMediaWindowRange,
|
||||
): Promise<PreviewSession> {
|
||||
const window = await ensureWindow(review, range);
|
||||
if (active !== review) {
|
||||
// The review ended during the download; do not start a player nobody will dispose.
|
||||
throw new Error('This timing review is no longer active.');
|
||||
}
|
||||
const mediaPath = window?.path ?? review.mediaPath;
|
||||
if (review.preview?.path === mediaPath) return review.preview.session;
|
||||
|
||||
const previous = review.preview;
|
||||
const session = deps.createPreviewSession();
|
||||
session.onPlaybackEnded(() => {
|
||||
if (active === review && review.preview?.session === started) {
|
||||
deps.onPreviewEnded?.(review.payload.reviewId);
|
||||
}
|
||||
});
|
||||
const { audioTrackId, ...previewOptions } = review.previewOptions;
|
||||
const started = session
|
||||
.start({
|
||||
mediaPath,
|
||||
...previewOptions,
|
||||
// A cached window keeps one audio stream, so mpv's track id from the source no longer applies.
|
||||
...(window
|
||||
? { absoluteTimestamps: true }
|
||||
: audioTrackId !== undefined
|
||||
? { audioTrackId }
|
||||
: {}),
|
||||
})
|
||||
.then(() => session)
|
||||
.catch((error) => {
|
||||
session.dispose();
|
||||
throw error;
|
||||
});
|
||||
review.preview = { path: mediaPath, session: started };
|
||||
void started.catch(() => {});
|
||||
if (previous) void previous.session.then((old) => old.dispose()).catch(() => {});
|
||||
return started;
|
||||
}
|
||||
|
||||
async function runReview(request: MediaTimingReviewRequest): Promise<MediaTimingReviewDecision> {
|
||||
const mpvClient = deps.getMpvClient();
|
||||
const mediaPath =
|
||||
@@ -208,11 +326,12 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
return { action: 'use-original' };
|
||||
}
|
||||
|
||||
const [pauseRaw, durationRaw, audioTrackRaw, volumeRaw] = await Promise.all([
|
||||
const [pauseRaw, durationRaw, audioTrackRaw, volumeRaw, resolvedSource] = await Promise.all([
|
||||
mpvClient.requestProperty?.('pause').catch(() => null) ?? null,
|
||||
mpvClient.requestProperty?.('duration').catch(() => null) ?? null,
|
||||
mpvClient.requestProperty?.('aid').catch(() => null) ?? null,
|
||||
mpvClient.requestProperty?.('volume').catch(() => null) ?? null,
|
||||
deps.resolveMediaSource?.().catch(() => null) ?? null,
|
||||
]);
|
||||
const pauseState = booleanProperty(pauseRaw);
|
||||
mpvClient.send({ command: ['set_property', 'pause', 'yes'] });
|
||||
@@ -232,38 +351,51 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
mediaDuration: finiteNumber(durationRaw) ?? undefined,
|
||||
...(contextLines ? { contextLines } : {}),
|
||||
});
|
||||
const previewSession = deps.createPreviewSession();
|
||||
const preview = previewSession
|
||||
.start({
|
||||
mediaPath,
|
||||
executablePath: deps.getMpvExecutablePath(),
|
||||
audioTrackId: finiteNumber(audioTrackRaw) ?? undefined,
|
||||
volume: finiteNumber(volumeRaw) ?? undefined,
|
||||
})
|
||||
.then(() => previewSession)
|
||||
.catch((error) => {
|
||||
previewSession.dispose();
|
||||
throw error;
|
||||
});
|
||||
void preview.catch(() => {});
|
||||
const sourcePath = resolvedSource?.path.trim() || mediaPath;
|
||||
const inputOptions = resolvedSource?.inputOptions;
|
||||
const audioStreamIndex =
|
||||
resolvedSource?.singleResolvedStream || mpvClient.currentAudioStreamIndex == null
|
||||
? undefined
|
||||
: mpvClient.currentAudioStreamIndex;
|
||||
const windowSource: RemoteMediaWindowSource | null =
|
||||
deps.acquireMediaWindow && isRemoteMediaWindowSourcePath(sourcePath)
|
||||
? {
|
||||
path: sourcePath,
|
||||
...(inputOptions ? { inputOptions } : {}),
|
||||
audioStreamIndex: audioStreamIndex ?? null,
|
||||
}
|
||||
: null;
|
||||
|
||||
let resolveDecision!: (decision: MediaTimingReviewDecision) => void;
|
||||
const decisionPromise = new Promise<MediaTimingReviewDecision>((resolve) => {
|
||||
resolveDecision = resolve;
|
||||
});
|
||||
active = {
|
||||
const review: ActiveReview = {
|
||||
payload,
|
||||
mediaPath,
|
||||
...(mpvClient.currentAudioStreamIndex !== null &&
|
||||
mpvClient.currentAudioStreamIndex !== undefined
|
||||
? { audioStreamIndex: mpvClient.currentAudioStreamIndex }
|
||||
: {}),
|
||||
waveformMedia: inputOptions ? { path: sourcePath, inputOptions } : sourcePath,
|
||||
...(audioStreamIndex !== undefined ? { audioStreamIndex } : {}),
|
||||
windowSource,
|
||||
window: null,
|
||||
windowRequest: null,
|
||||
windowFailed: false,
|
||||
previewOptions: {
|
||||
executablePath: deps.getMpvExecutablePath(),
|
||||
audioTrackId: finiteNumber(audioTrackRaw) ?? undefined,
|
||||
volume: finiteNumber(volumeRaw) ?? undefined,
|
||||
},
|
||||
preview: null,
|
||||
mpvClient,
|
||||
restorePlayback: pendingPauseRestore === mpvClient,
|
||||
preview,
|
||||
resolve: resolveDecision,
|
||||
};
|
||||
active = review;
|
||||
pendingPauseRestore = null;
|
||||
// Download the visible timeline once now; the waveform and preview both wait on it.
|
||||
void previewFor(review, {
|
||||
startTime: payload.timelineStartTime,
|
||||
endTime: payload.timelineEndTime,
|
||||
}).catch(() => {});
|
||||
|
||||
const opened = await deps.openModal(payload).catch(() => false);
|
||||
if (!opened) {
|
||||
@@ -317,7 +449,10 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
return { ok: false, message: 'The selected preview range is invalid.' };
|
||||
}
|
||||
try {
|
||||
const previewSession = await current.preview;
|
||||
const previewSession = await previewFor(current, request);
|
||||
if (active !== current) {
|
||||
return { ok: false, message: 'This timing review is no longer active.' };
|
||||
}
|
||||
await previewSession.play(request.startTime, request.endTime);
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
@@ -347,11 +482,15 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
}
|
||||
|
||||
try {
|
||||
const window = await ensureWindow(current, request);
|
||||
if (active !== current) {
|
||||
return { ok: false, message: 'This timing review is no longer active.' };
|
||||
}
|
||||
const peaks = await deps.generateWaveform({
|
||||
mediaPath: current.mediaPath,
|
||||
mediaPath: window?.media ?? current.waveformMedia,
|
||||
startTime: request.startTime,
|
||||
endTime: request.endTime,
|
||||
...(current.audioStreamIndex !== undefined
|
||||
...(!window && current.audioStreamIndex !== undefined
|
||||
? { audioStreamIndex: current.audioStreamIndex }
|
||||
: {}),
|
||||
});
|
||||
@@ -370,8 +509,8 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
return { ok: false, message: 'This timing review is no longer active.' };
|
||||
}
|
||||
try {
|
||||
const previewSession = await current.preview;
|
||||
await previewSession.stop();
|
||||
const previewSession = current.preview ? await current.preview.session : null;
|
||||
await previewSession?.stop();
|
||||
return { ok: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -403,7 +542,7 @@ export function createMediaTimingReviewRuntime(deps: MediaTimingReviewRuntimeDep
|
||||
const current = active;
|
||||
active = null;
|
||||
if (!current) return;
|
||||
void current.preview.then((session) => session.dispose()).catch(() => {});
|
||||
void current.preview?.session.then((session) => session.dispose()).catch(() => {});
|
||||
if (current.restorePlayback && current.mpvClient.connected) {
|
||||
current.mpvClient.send({ command: ['set_property', 'pause', 'no'] });
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import test from 'node:test';
|
||||
import { parseSubtitleCues } from '../../core/services/subtitle-cue-parser';
|
||||
import {
|
||||
resolveCanonicalPrimarySubtitle,
|
||||
resolvePrimarySubtitle,
|
||||
resolvePrimarySubtitleText,
|
||||
stripCanonicalFragmentLines,
|
||||
} from './primary-subtitle-text';
|
||||
@@ -702,3 +703,37 @@ test('resolvePrimarySubtitleText publishes a wrapped caption sentence as one cue
|
||||
'(東)≪好きだと\n自覚してしまったものの➡',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolvePrimarySubtitle drops a finished caption row lingering beside a fresh line', () => {
|
||||
// Broadcast captions give each row its own event, and a row of the previous line can
|
||||
// outlive its siblings by a frame. mpv's sub-text still lists it, so the mined line
|
||||
// must come from the parsed cue that is actually running, with that cue's timings.
|
||||
const ass = [
|
||||
'[Script Info]',
|
||||
'PlayResY: 540',
|
||||
'',
|
||||
'[Events]',
|
||||
'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text',
|
||||
'Dialogue: 0,0:14:30.00,0:14:33.00,Default,,0,0,0,,{\\pos(232,437)\\fscx50}({\\fscx100}東{\\fscx50}){\\fscx100}ずっと 言えなかっ',
|
||||
'Dialogue: 0,0:14:30.00,0:14:33.02,Default,,0,0,0,,{\\pos(232,497)}たが',
|
||||
'Dialogue: 0,0:14:33.00,0:14:36.00,Default,,0,0,0,,{\\pos(232,437)}⸨もし お互い',
|
||||
'Dialogue: 0,0:14:33.00,0:14:36.00,Default,,0,0,0,,{\\pos(232,497)}本命 受かったら 大学 近いし➡',
|
||||
].join('\n');
|
||||
const cues = parseSubtitleCues(ass, 'polar-opposites-s02e09.ass');
|
||||
|
||||
const resolved = resolvePrimarySubtitle({
|
||||
liveText: 'たが\n⸨もし お互い\n本命 受かったら 大学 近いし➡',
|
||||
currentTimeSec: 14 * 60 + 33.05,
|
||||
cues,
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
{ ...resolved, cues: resolved?.cues.map((cue) => cue.text) },
|
||||
{
|
||||
text: '⸨もし お互い\n本命 受かったら 大学 近いし➡',
|
||||
startTime: 14 * 60 + 33,
|
||||
endTime: 14 * 60 + 36,
|
||||
cues: ['⸨もし お互い\n本命 受かったら 大学 近いし➡'],
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -319,6 +319,26 @@ export function resolveRecordedPrimarySubtitleText(options: {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The parsed view of the live text with its cue timings: a canonical animation when one
|
||||
* explains the live lines, otherwise the active parsed cues. Null when the parsed cues
|
||||
* cannot account for every live line, in which case callers keep the raw mpv text.
|
||||
*/
|
||||
export function resolvePrimarySubtitle(options: {
|
||||
liveText: string;
|
||||
currentTimeSec: number;
|
||||
cues: readonly SubtitleCue[] | null | undefined;
|
||||
}): ResolvedPrimarySubtitle | null {
|
||||
const liveText = decodedLiveText(options.liveText, options.cues);
|
||||
if (!liveText.trim()) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
resolveCanonicalPrimarySubtitle({ ...options, liveText }) ??
|
||||
resolveActiveParsedPrimarySubtitle({ ...options, liveText })
|
||||
);
|
||||
}
|
||||
|
||||
export function resolvePrimarySubtitleText(options: {
|
||||
liveText: string;
|
||||
currentTimeSec: number;
|
||||
@@ -328,13 +348,5 @@ export function resolvePrimarySubtitleText(options: {
|
||||
if (!liveText.trim()) {
|
||||
return liveText;
|
||||
}
|
||||
return (
|
||||
resolveCanonicalPrimarySubtitle({
|
||||
liveText,
|
||||
currentTimeSec: options.currentTimeSec,
|
||||
cues: options.cues,
|
||||
})?.text ??
|
||||
resolveActiveParsedPrimarySubtitle({ ...options, liveText })?.text ??
|
||||
removeLiveGlyphFragmentLines(liveText)
|
||||
);
|
||||
return resolvePrimarySubtitle(options)?.text ?? removeLiveGlyphFragmentLines(liveText);
|
||||
}
|
||||
|
||||
+141
-31
@@ -10,6 +10,9 @@ import {
|
||||
MediaGenerator,
|
||||
type MediaGeneratorOptions,
|
||||
} from './media-generator';
|
||||
import { RemoteMediaWindowCache } from './core/services/remote-media-window-cache';
|
||||
|
||||
const REMOTE_STREAM_URL = 'https://jellyfin.example/Videos/abc/stream?static=true';
|
||||
|
||||
async function withStubbedFfmpeg(
|
||||
run: (generator: MediaGenerator, argsPath: string) => Promise<void>,
|
||||
@@ -21,6 +24,7 @@ async function withStubbedFfmpeg(
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-media-generator-test-'));
|
||||
const binDir = path.join(root, 'bin');
|
||||
const tempDir = path.join(root, 'media');
|
||||
const windowsDir = path.join(root, 'windows');
|
||||
const argsPath = path.join(root, 'ffmpeg-args.txt');
|
||||
fs.mkdirSync(binDir, { recursive: true });
|
||||
const ffmpegStubPath = path.join(binDir, 'ffmpeg-stub.cjs');
|
||||
@@ -34,7 +38,7 @@ async function withStubbedFfmpeg(
|
||||
" console.log(' V..... libaom-av1');",
|
||||
' process.exit(0);',
|
||||
'}',
|
||||
"fs.writeFileSync(process.env.SUBMINER_TEST_FFMPEG_ARGS, JSON.stringify(args), 'utf8');",
|
||||
"fs.appendFileSync(process.env.SUBMINER_TEST_FFMPEG_ARGS, JSON.stringify(args) + '\\n', 'utf8');",
|
||||
'const outputPath = args.at(-1);',
|
||||
"if (process.env.SUBMINER_TEST_FFMPEG_SKIP_OUTPUT !== '1') {",
|
||||
" fs.writeFileSync(outputPath, 'avif', 'utf8');",
|
||||
@@ -61,12 +65,18 @@ async function withStubbedFfmpeg(
|
||||
} else {
|
||||
delete process.env.SUBMINER_TEST_FFMPEG_SKIP_OUTPUT;
|
||||
}
|
||||
const generator = new MediaGenerator(tempDir, options);
|
||||
// Each test gets its own window cache so remote inputs never leak windows between tests.
|
||||
const remoteMediaWindows = new RemoteMediaWindowCache({ tempDir: windowsDir, idleTtlMs: 0 });
|
||||
const generator = new MediaGenerator(tempDir, {
|
||||
remoteMediaWindows,
|
||||
...options,
|
||||
});
|
||||
|
||||
try {
|
||||
await run(generator, argsPath);
|
||||
} finally {
|
||||
generator.cleanup();
|
||||
remoteMediaWindows.cleanup();
|
||||
process.env.PATH = originalPath;
|
||||
if (originalArgsPath === undefined) {
|
||||
delete process.env.SUBMINER_TEST_FFMPEG_ARGS;
|
||||
@@ -82,8 +92,17 @@ async function withStubbedFfmpeg(
|
||||
}
|
||||
}
|
||||
|
||||
function readAllFfmpegArgs(argsPath: string): string[][] {
|
||||
return fs
|
||||
.readFileSync(argsPath, 'utf8')
|
||||
.split('\n')
|
||||
.filter((line) => line.trim().length > 0)
|
||||
.map((line) => JSON.parse(line) as string[]);
|
||||
}
|
||||
|
||||
/** Arguments of the most recent ffmpeg invocation. */
|
||||
function readFfmpegArgs(argsPath: string): string[] {
|
||||
return JSON.parse(fs.readFileSync(argsPath, 'utf8')) as string[];
|
||||
return readAllFfmpegArgs(argsPath).at(-1) ?? [];
|
||||
}
|
||||
|
||||
test('buildAnimatedImageVideoFilter holds lead-in until the next frame after the audio boundary', () => {
|
||||
@@ -272,41 +291,131 @@ test('generateAudio recreates missing temp directory before invoking ffmpeg', as
|
||||
});
|
||||
|
||||
test('generateAudio adds remote input options before the ffmpeg input', async () => {
|
||||
await withStubbedFfmpeg(async (generator, argsPath) => {
|
||||
await generator.generateAudio(
|
||||
{
|
||||
path: 'https://rr1---sn.example.googlevideo.com/videoplayback?mime=audio%2Fwebm',
|
||||
inputOptions: {
|
||||
reconnect: true,
|
||||
userAgent: 'Mozilla/5.0',
|
||||
headers: {
|
||||
Referer: 'https://www.youtube.com/',
|
||||
Origin: 'https://www.youtube.com',
|
||||
await withStubbedFfmpeg(
|
||||
async (generator, argsPath) => {
|
||||
await generator.generateAudio(
|
||||
{
|
||||
path: 'https://rr1---sn.example.googlevideo.com/videoplayback?mime=audio%2Fwebm',
|
||||
inputOptions: {
|
||||
reconnect: true,
|
||||
userAgent: 'Mozilla/5.0',
|
||||
headers: {
|
||||
Referer: 'https://www.youtube.com/',
|
||||
Origin: 'https://www.youtube.com',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
10,
|
||||
12,
|
||||
);
|
||||
|
||||
const args = readFfmpegArgs(argsPath);
|
||||
const inputIndex = args.indexOf('-i');
|
||||
assert.ok(inputIndex > 0);
|
||||
assert.ok(args.indexOf('-reconnect') > -1);
|
||||
assert.ok(args.indexOf('-reconnect') < inputIndex);
|
||||
assert.equal(args[args.indexOf('-reconnect') + 1], '1');
|
||||
assert.equal(args[args.indexOf('-reconnect_streamed') + 1], '1');
|
||||
assert.equal(args[args.indexOf('-reconnect_on_network_error') + 1], '1');
|
||||
assert.equal(args[args.indexOf('-reconnect_on_http_error') + 1], '403,5xx');
|
||||
assert.equal(args[args.indexOf('-reconnect_delay_max') + 1], '5');
|
||||
assert.equal(args[args.indexOf('-user_agent') + 1], 'Mozilla/5.0');
|
||||
assert.equal(
|
||||
args[args.indexOf('-headers') + 1],
|
||||
'Referer: https://www.youtube.com/\r\nOrigin: https://www.youtube.com\r\n',
|
||||
);
|
||||
},
|
||||
{ remoteMediaWindows: null },
|
||||
);
|
||||
});
|
||||
|
||||
test('generateAudio downloads a remote window once and extracts from it with absolute seeks', async () => {
|
||||
await withStubbedFfmpeg(async (generator, argsPath) => {
|
||||
await generator.generateAudio(
|
||||
{ path: REMOTE_STREAM_URL, inputOptions: { reconnect: true } },
|
||||
10,
|
||||
12,
|
||||
0.5,
|
||||
2,
|
||||
);
|
||||
|
||||
const args = readFfmpegArgs(argsPath);
|
||||
const inputIndex = args.indexOf('-i');
|
||||
assert.ok(inputIndex > 0);
|
||||
assert.ok(args.indexOf('-reconnect') > -1);
|
||||
assert.ok(args.indexOf('-reconnect') < inputIndex);
|
||||
assert.equal(args[args.indexOf('-reconnect') + 1], '1');
|
||||
assert.equal(args[args.indexOf('-reconnect_streamed') + 1], '1');
|
||||
assert.equal(args[args.indexOf('-reconnect_on_network_error') + 1], '1');
|
||||
assert.equal(args[args.indexOf('-reconnect_on_http_error') + 1], '403,5xx');
|
||||
assert.equal(args[args.indexOf('-reconnect_delay_max') + 1], '5');
|
||||
assert.equal(args[args.indexOf('-user_agent') + 1], 'Mozilla/5.0');
|
||||
assert.equal(
|
||||
args[args.indexOf('-headers') + 1],
|
||||
'Referer: https://www.youtube.com/\r\nOrigin: https://www.youtube.com\r\n',
|
||||
);
|
||||
const calls = readAllFfmpegArgs(argsPath);
|
||||
assert.equal(calls.length, 2);
|
||||
const [fetchArgs, audioArgs] = calls as [string[], string[]];
|
||||
assert.equal(fetchArgs[fetchArgs.indexOf('-i') + 1], REMOTE_STREAM_URL);
|
||||
assert.ok(fetchArgs.indexOf('-reconnect') < fetchArgs.indexOf('-i'));
|
||||
assert.equal(fetchArgs[fetchArgs.indexOf('-ss') + 1], '9.25');
|
||||
assert.equal(fetchArgs[fetchArgs.lastIndexOf('-map') + 1], '0:2');
|
||||
assert.ok(fetchArgs.includes('-copyts'));
|
||||
|
||||
const windowPath = audioArgs[audioArgs.indexOf('-i') + 1];
|
||||
assert.ok(windowPath?.endsWith('.mkv'));
|
||||
assert.notEqual(windowPath, REMOTE_STREAM_URL);
|
||||
assert.equal(audioArgs[audioArgs.indexOf('-ss') + 1], '9.5');
|
||||
assert.equal(audioArgs[audioArgs.indexOf('-seek_timestamp') + 1], '1');
|
||||
assert.ok(audioArgs.indexOf('-seek_timestamp') < audioArgs.indexOf('-i'));
|
||||
assert.equal(audioArgs.includes('-reconnect'), false);
|
||||
assert.equal(audioArgs.includes('-map'), false);
|
||||
assert.equal(audioArgs.includes('-probesize'), false);
|
||||
assert.ok(audioArgs.includes('loudnorm=I=-23:TP=-2:LRA=11'));
|
||||
});
|
||||
});
|
||||
|
||||
test('generateScreenshot reuses a downloaded window but never downloads one itself', async () => {
|
||||
await withStubbedFfmpeg(async (generator, argsPath) => {
|
||||
await generator.generateScreenshot(REMOTE_STREAM_URL, 11, { format: 'jpg' });
|
||||
let calls = readAllFfmpegArgs(argsPath);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0]![calls[0]!.indexOf('-i') + 1], REMOTE_STREAM_URL);
|
||||
|
||||
await generator.generateAudio(REMOTE_STREAM_URL, 10, 12);
|
||||
await generator.generateScreenshot(REMOTE_STREAM_URL, 11, { format: 'jpg' });
|
||||
await generator.generateScreenshot(REMOTE_STREAM_URL, 40, { format: 'jpg' });
|
||||
|
||||
calls = readAllFfmpegArgs(argsPath);
|
||||
assert.equal(calls.length, 5);
|
||||
const insideWindow = calls[3]!;
|
||||
assert.ok(insideWindow[insideWindow.indexOf('-i') + 1]?.endsWith('.mkv'));
|
||||
assert.equal(insideWindow[insideWindow.indexOf('-seek_timestamp') + 1], '1');
|
||||
const outsideWindow = calls[4]!;
|
||||
assert.equal(outsideWindow[outsideWindow.indexOf('-i') + 1], REMOTE_STREAM_URL);
|
||||
});
|
||||
});
|
||||
|
||||
test('generateAnimatedImage downloads the clip window before encoding', async () => {
|
||||
await withStubbedFfmpeg(async (generator, argsPath) => {
|
||||
await generator.generateAnimatedImage(REMOTE_STREAM_URL, 10, 12, 0, { fps: 10 });
|
||||
|
||||
const calls = readAllFfmpegArgs(argsPath).filter(
|
||||
(args) => args[0] !== '-hide_banner' || args[1] !== '-encoders',
|
||||
);
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(calls[0]![calls[0]!.indexOf('-i') + 1], REMOTE_STREAM_URL);
|
||||
assert.ok(calls[1]![calls[1]!.indexOf('-i') + 1]?.endsWith('.mkv'));
|
||||
assert.equal(calls[1]![calls[1]!.indexOf('-seek_timestamp') + 1], '1');
|
||||
});
|
||||
});
|
||||
|
||||
test('generateAudio reads the remote source directly when the window download fails', async () => {
|
||||
await withStubbedFfmpeg(
|
||||
async (generator, argsPath) => {
|
||||
await generator.generateAudio(REMOTE_STREAM_URL, 10, 12);
|
||||
|
||||
const args = readFfmpegArgs(argsPath);
|
||||
assert.equal(args[args.indexOf('-i') + 1], REMOTE_STREAM_URL);
|
||||
assert.equal(args.includes('-seek_timestamp'), false);
|
||||
},
|
||||
{
|
||||
remoteMediaWindows: new RemoteMediaWindowCache({
|
||||
execFile: (_file, _args, _options, callback) =>
|
||||
queueMicrotask(() => callback(Object.assign(new Error('offline'), { code: 1 }))),
|
||||
idleTtlMs: 0,
|
||||
logDebug: () => undefined,
|
||||
}),
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('generateAudio skips stale audio stream maps for single resolved streams', async () => {
|
||||
await withStubbedFfmpeg(async (generator, argsPath) => {
|
||||
await generator.generateAudio(
|
||||
@@ -320,8 +429,9 @@ test('generateAudio skips stale audio stream maps for single resolved streams',
|
||||
22,
|
||||
);
|
||||
|
||||
const args = readFfmpegArgs(argsPath);
|
||||
assert.equal(args.includes('-map'), false);
|
||||
const [fetchArgs, audioArgs] = readAllFfmpegArgs(argsPath) as [string[], string[]];
|
||||
assert.equal(fetchArgs[fetchArgs.lastIndexOf('-map') + 1], '0:a');
|
||||
assert.equal(audioArgs.includes('-map'), false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+84
-3
@@ -22,6 +22,12 @@ import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import { createLogger } from './logger';
|
||||
import { normalizeMediaInput, type MediaInput } from './media-input';
|
||||
import {
|
||||
getSharedRemoteMediaWindowCache,
|
||||
isRemoteMediaWindowSourcePath,
|
||||
type RemoteMediaWindowCache,
|
||||
type RemoteMediaWindowRange,
|
||||
} from './core/services/remote-media-window-cache';
|
||||
|
||||
const log = createLogger('media');
|
||||
const AUDIO_NORMALIZATION_FILTER = 'loudnorm=I=-23:TP=-2:LRA=11';
|
||||
@@ -86,6 +92,11 @@ export interface MediaGeneratorOptions {
|
||||
logDebug?: (message: string) => void;
|
||||
now?: () => number;
|
||||
execFile?: MediaGeneratorExecFile;
|
||||
/**
|
||||
* Local window cache for http(s) sources. Defaults to the process-wide cache shared
|
||||
* with the timing review; pass `null` to always read remote sources directly.
|
||||
*/
|
||||
remoteMediaWindows?: RemoteMediaWindowCache | null;
|
||||
}
|
||||
|
||||
function sanitizeDebugToken(value: string, fallback: string): string {
|
||||
@@ -232,6 +243,54 @@ export class MediaGenerator {
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps an http(s) input for the locally cached window that covers `range`, so the
|
||||
* clip is downloaded once instead of per FFmpeg run. `acquire` downloads on a miss;
|
||||
* `lookup` only reuses a window that another step already fetched. Any failure falls
|
||||
* back to reading the remote source directly.
|
||||
*/
|
||||
private async resolveRemoteWindowInput(
|
||||
input: MediaInput,
|
||||
range: RemoteMediaWindowRange,
|
||||
audioStreamIndex: number | null | undefined,
|
||||
mode: 'acquire' | 'lookup',
|
||||
): Promise<MediaInput> {
|
||||
const cache =
|
||||
this.options.remoteMediaWindows === undefined
|
||||
? getSharedRemoteMediaWindowCache()
|
||||
: this.options.remoteMediaWindows;
|
||||
const sourcePath = typeof input === 'string' ? input : input.path;
|
||||
if (!cache || !isRemoteMediaWindowSourcePath(sourcePath)) {
|
||||
return input;
|
||||
}
|
||||
const source = {
|
||||
path: sourcePath,
|
||||
...(typeof input === 'object' && input.inputOptions
|
||||
? { inputOptions: input.inputOptions }
|
||||
: {}),
|
||||
audioStreamIndex:
|
||||
typeof input === 'object' && input.singleResolvedStream ? null : (audioStreamIndex ?? null),
|
||||
};
|
||||
const description = describeMediaInputForDebugLog(input);
|
||||
try {
|
||||
const window =
|
||||
mode === 'acquire' ? await cache.acquire(source, range) : await cache.lookup(source, range);
|
||||
if (!window) {
|
||||
this.logMediaDebug(`window miss ${description} mode=${mode}`);
|
||||
return input;
|
||||
}
|
||||
this.logMediaDebug(
|
||||
`window hit ${description} mode=${mode} start=${window.startTime} end=${window.endTime}`,
|
||||
);
|
||||
return window.media;
|
||||
} catch (error) {
|
||||
this.logMediaDebug(
|
||||
`window failed ${description} mode=${mode} reason=${sanitizeDebugToken((error as Error).message, 'error')}`,
|
||||
);
|
||||
return input;
|
||||
}
|
||||
}
|
||||
|
||||
private ffmpegError(label: string, error: ExecFileException): Error {
|
||||
if (error.code === 'ENOENT') {
|
||||
return new Error('FFmpeg not found. Install FFmpeg to enable media generation.');
|
||||
@@ -281,7 +340,13 @@ export class MediaGenerator {
|
||||
const safePadding = Number.isFinite(padding) ? Math.max(0, padding) : 0;
|
||||
const start = Math.max(0, startTime - safePadding);
|
||||
const duration = endTime - start + safePadding;
|
||||
const mediaInput = normalizeMediaInput(videoPath);
|
||||
const sourceInput = await this.resolveRemoteWindowInput(
|
||||
videoPath,
|
||||
{ startTime: start, endTime: start + duration },
|
||||
audioStreamIndex,
|
||||
'acquire',
|
||||
);
|
||||
const mediaInput = normalizeMediaInput(sourceInput);
|
||||
const inputDescription = describeMediaInputForDebugLog(videoPath);
|
||||
const hasSelectedAudioStream =
|
||||
!mediaInput.singleResolvedStream &&
|
||||
@@ -385,7 +450,15 @@ export class MediaGenerator {
|
||||
png: 'png',
|
||||
webp: 'webp',
|
||||
};
|
||||
const mediaInput = normalizeMediaInput(videoPath);
|
||||
// A single frame is cheap to fetch remotely, so only reuse a window another step downloaded.
|
||||
const mediaInput = normalizeMediaInput(
|
||||
await this.resolveRemoteWindowInput(
|
||||
videoPath,
|
||||
{ startTime: timestamp, endTime: timestamp },
|
||||
null,
|
||||
'lookup',
|
||||
),
|
||||
);
|
||||
const inputDescription = describeMediaInputForDebugLog(videoPath);
|
||||
|
||||
const args: string[] = [
|
||||
@@ -533,9 +606,17 @@ export class MediaGenerator {
|
||||
);
|
||||
}
|
||||
|
||||
const mediaInput = normalizeMediaInput(
|
||||
await this.resolveRemoteWindowInput(
|
||||
videoPath,
|
||||
{ startTime: start, endTime: start + duration },
|
||||
null,
|
||||
'acquire',
|
||||
),
|
||||
);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const outputPath = this.createTempOutputPath('animation', 'avif');
|
||||
const mediaInput = normalizeMediaInput(videoPath);
|
||||
const startedAt = this.nowMs();
|
||||
|
||||
const encoderArgs: string[] = ['-c:v', av1Encoder];
|
||||
|
||||
@@ -11,6 +11,12 @@ export type MediaInput =
|
||||
source?: string;
|
||||
inputOptions?: MediaInputOptions;
|
||||
singleResolvedStream?: boolean;
|
||||
/**
|
||||
* The file keeps the original media timestamps instead of starting at zero (a
|
||||
* stream-copied window of a longer source). Seek with `-ss` against those
|
||||
* absolute timestamps rather than relative to the file's own start time.
|
||||
*/
|
||||
absoluteTimestamps?: boolean;
|
||||
};
|
||||
|
||||
export type NormalizedMediaInput = {
|
||||
@@ -89,6 +95,10 @@ export function normalizeMediaInput(input: MediaInput): NormalizedMediaInput {
|
||||
inputArgs.push('-headers', headers);
|
||||
}
|
||||
|
||||
if (input.absoluteTimestamps) {
|
||||
inputArgs.push('-seek_timestamp', '1');
|
||||
}
|
||||
|
||||
return {
|
||||
path: input.path,
|
||||
inputArgs,
|
||||
|
||||
@@ -191,6 +191,10 @@ const onOpenMediaTimingReviewEvent =
|
||||
IPC_CHANNELS.event.mediaTimingReviewOpen,
|
||||
(payload) => payload as MediaTimingReviewOpenPayload,
|
||||
);
|
||||
const onMediaTimingReviewPreviewEndedEvent = createQueuedIpcListenerWithPayload<string>(
|
||||
IPC_CHANNELS.event.mediaTimingReviewPreviewEnded,
|
||||
(payload) => (typeof payload === 'string' ? payload : ''),
|
||||
);
|
||||
const onOpenPlaylistBrowserEvent = createQueuedIpcListener(IPC_CHANNELS.event.playlistBrowserOpen);
|
||||
const onCancelYoutubeTrackPickerEvent = createQueuedIpcListener(
|
||||
IPC_CHANNELS.event.youtubePickerCancel,
|
||||
@@ -469,6 +473,7 @@ const electronAPI: ElectronAPI = {
|
||||
onOpenTsukihime: onOpenTsukihimeEvent,
|
||||
onOpenYoutubeTrackPicker: onOpenYoutubeTrackPickerEvent,
|
||||
onOpenMediaTimingReview: onOpenMediaTimingReviewEvent,
|
||||
onMediaTimingReviewPreviewEnded: onMediaTimingReviewPreviewEndedEvent,
|
||||
previewMediaTimingReview: (
|
||||
request: MediaTimingReviewPreviewRequest,
|
||||
): Promise<MediaTimingReviewActionResult> =>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
formatMediaTimingTimestamp,
|
||||
mediaTimingTimeFromPointer,
|
||||
slideMediaTimingSelection,
|
||||
trimMediaTimingSelectionEnd,
|
||||
} from './media-timing-review';
|
||||
|
||||
test('waveform path mirrors normalized peaks around its center line', () => {
|
||||
@@ -122,3 +123,35 @@ test('preview request guard blocks overlap and invalidates stale responses', ()
|
||||
guard.finish(second!);
|
||||
assert.equal(guard.isInFlight(), false);
|
||||
});
|
||||
|
||||
test('trailing silence trim follows the last speech slice and keeps cut-off or silent lines', () => {
|
||||
// 10 slices over a 10 s timeline: one slice per second, speech in seconds 2-4 only.
|
||||
const peaks = [0, 0, 0.9, 0.8, 0.7, 0.1, 0.2, 0, 0, 0];
|
||||
const base = { peaks, timelineStart: 0, timelineEnd: 10, lineStart: 2, lineEnd: 8 };
|
||||
|
||||
const trimmed = trimMediaTimingSelectionEnd({ ...base, selectionEnd: 8, endPadSeconds: 0 });
|
||||
assert.ok(trimmed !== null && Math.abs(trimmed - 5.15) < 1e-9);
|
||||
|
||||
const padded = trimMediaTimingSelectionEnd({ ...base, selectionEnd: 8.5, endPadSeconds: 0.5 });
|
||||
assert.ok(padded !== null && Math.abs(padded - 5.65) < 1e-9);
|
||||
|
||||
// Speech running through the line end means the subtitle cuts the audio off; keep it.
|
||||
assert.equal(
|
||||
trimMediaTimingSelectionEnd({ ...base, lineEnd: 5, selectionEnd: 5, endPadSeconds: 0 }),
|
||||
null,
|
||||
);
|
||||
// No speech inside the line at all: keep the subtitle timing rather than guess.
|
||||
assert.equal(
|
||||
trimMediaTimingSelectionEnd({ ...base, lineStart: 6, selectionEnd: 8, endPadSeconds: 0 }),
|
||||
null,
|
||||
);
|
||||
// A saving below the minimum trim is not worth moving the handle for.
|
||||
assert.equal(
|
||||
trimMediaTimingSelectionEnd({ ...base, lineEnd: 5.2, selectionEnd: 5.2, endPadSeconds: 0 }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
trimMediaTimingSelectionEnd({ ...base, peaks: [1], selectionEnd: 8, endPadSeconds: 0 }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -11,6 +11,16 @@ const FINE_ADJUST_SECONDS = 0.1;
|
||||
const COARSE_ADJUST_SECONDS = 0.5;
|
||||
const TIMELINE_EXPANSION_SECONDS = 2;
|
||||
const LINE_REVEAL_MARGIN_SECONDS = 1;
|
||||
/**
|
||||
* Subtitles usually linger past the dialogue for readability, so an untouched clip end
|
||||
* follows the last speech-weighted waveform slice above this level (0..1, relative to the
|
||||
* clip's own noise floor) plus a short tail, when that saves at least the minimum trim.
|
||||
*/
|
||||
const SPEECH_LEVEL_THRESHOLD = 0.3;
|
||||
const SPEECH_TAIL_SECONDS = 0.15;
|
||||
const MINIMUM_TRAILING_TRIM_SECONDS = 0.1;
|
||||
/** Slack past the clip length before the UI gives up waiting for mpv's end-of-clip signal. */
|
||||
const PREVIEW_END_GRACE_MS = 2_500;
|
||||
|
||||
function clamp(value: number, minimum: number, maximum: number): number {
|
||||
return Math.min(maximum, Math.max(minimum, value));
|
||||
@@ -105,6 +115,48 @@ export function buildMediaTimingWaveformPath(peaks: number[]): string {
|
||||
return `M ${upper.join(' L ')} L ${lower.join(' L ')} Z`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an untouched clip should end once the waveform is known: just after the line's
|
||||
* last speech slice, plus the configured end padding. Null keeps the subtitle timing when
|
||||
* no speech shows inside the line, when speech runs through the line end (the subtitle is
|
||||
* cutting the audio off, not lingering), or when the saving is too small to matter.
|
||||
*/
|
||||
export function trimMediaTimingSelectionEnd(options: {
|
||||
peaks: readonly number[];
|
||||
timelineStart: number;
|
||||
timelineEnd: number;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
selectionEnd: number;
|
||||
endPadSeconds: number;
|
||||
}): number | null {
|
||||
const pointCount = options.peaks.length;
|
||||
const span = options.timelineEnd - options.timelineStart;
|
||||
if (pointCount < 2 || span <= 0 || options.lineEnd <= options.lineStart) return null;
|
||||
// Point i covers [i, i + 1) / pointCount of the timeline (see computeWaveformPeaks).
|
||||
const sliceEnd = (index: number): number =>
|
||||
options.timelineStart + ((index + 1) / pointCount) * span;
|
||||
const firstIndex = Math.max(
|
||||
0,
|
||||
Math.floor(((options.lineStart - options.timelineStart) / span) * pointCount),
|
||||
);
|
||||
const lastIndex = Math.min(
|
||||
pointCount - 1,
|
||||
Math.ceil(((options.lineEnd - options.timelineStart) / span) * pointCount) - 1,
|
||||
);
|
||||
let lastSpeechIndex = -1;
|
||||
for (let index = lastIndex; index >= firstIndex; index -= 1) {
|
||||
if ((options.peaks[index] ?? 0) >= SPEECH_LEVEL_THRESHOLD) {
|
||||
lastSpeechIndex = index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastSpeechIndex === -1 || lastSpeechIndex >= lastIndex) return null;
|
||||
const trimmedEnd = sliceEnd(lastSpeechIndex) + SPEECH_TAIL_SECONDS + options.endPadSeconds;
|
||||
if (options.selectionEnd - trimmedEnd < MINIMUM_TRAILING_TRIM_SECONDS) return null;
|
||||
return trimmedEnd;
|
||||
}
|
||||
|
||||
export function constrainMediaTimingSelection(options: {
|
||||
nextStart: number;
|
||||
nextEnd: number;
|
||||
@@ -174,6 +226,8 @@ export function createMediaTimingReviewModal(
|
||||
let nextCount = 0;
|
||||
let startPadSeconds = 0;
|
||||
let endPadSeconds = 0;
|
||||
/** True until the user moves the clip; the first waveform then trims trailing silence. */
|
||||
let trailingTrimPending = false;
|
||||
let resolveInFlight = false;
|
||||
let previewPlaying = false;
|
||||
let previewTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -209,7 +263,11 @@ export function createMediaTimingReviewModal(
|
||||
previewTimer = null;
|
||||
}
|
||||
|
||||
/** Drives the play button label plus the playhead sweep that mirrors the hidden audio player. */
|
||||
/**
|
||||
* Drives the play button label plus the playhead sweep that mirrors the hidden audio player.
|
||||
* mpv reports when the clip actually finishes (see handlePreviewEnded), which accounts for
|
||||
* output latency such as Bluetooth headphones; the timer only covers a player that never does.
|
||||
*/
|
||||
function setPreviewPlaying(playing: boolean): void {
|
||||
previewPlaying = playing;
|
||||
ctx.dom.mediaTimingReviewPlayLabel.textContent = playing ? 'Stop preview' : 'Play selection';
|
||||
@@ -222,7 +280,14 @@ export function createMediaTimingReviewModal(
|
||||
track.style.setProperty('--playhead-duration', `${clipSeconds}s`);
|
||||
void track.offsetWidth;
|
||||
track.classList.add('is-previewing');
|
||||
previewTimer = setTimeout(() => stopPreview(), clipSeconds * 1000);
|
||||
previewTimer = setTimeout(() => stopPreview(), clipSeconds * 1000 + PREVIEW_END_GRACE_MS);
|
||||
}
|
||||
|
||||
/** The hidden player reached the end of the clip and paused itself. */
|
||||
function handlePreviewEnded(reviewId: string): void {
|
||||
if (!payload || payload.reviewId !== reviewId || !previewPlaying) return;
|
||||
setPreviewPlaying(false);
|
||||
setStatus('');
|
||||
}
|
||||
|
||||
/** Callers that need to report a failure set their own status after stopping the preview. */
|
||||
@@ -329,6 +394,7 @@ export function createMediaTimingReviewModal(
|
||||
}
|
||||
ctx.dom.mediaTimingReviewWaveformPath.setAttribute('d', path);
|
||||
setWaveformState('ready');
|
||||
trimTrailingSilence(result.peaks ?? []);
|
||||
} catch {
|
||||
if (sequence === waveformSequence && payload?.reviewId === reviewId) {
|
||||
setWaveformState('unavailable');
|
||||
@@ -336,6 +402,29 @@ export function createMediaTimingReviewModal(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves an untouched clip end back to where the line's dialogue ends. The Line end
|
||||
* rail keeps marking the subtitle timing, and Reset restores it.
|
||||
*/
|
||||
function trimTrailingSilence(peaks: readonly number[]): void {
|
||||
if (!payload || !trailingTrimPending || previewPlaying || previewRequest.isInFlight()) {
|
||||
return;
|
||||
}
|
||||
const lineRange = currentLineSelection();
|
||||
const trimmedEnd = trimMediaTimingSelectionEnd({
|
||||
peaks,
|
||||
timelineStart,
|
||||
timelineEnd,
|
||||
lineStart: lineRange.rangeStart,
|
||||
lineEnd: lineRange.rangeEnd,
|
||||
selectionEnd,
|
||||
endPadSeconds,
|
||||
});
|
||||
if (trimmedEnd === null) return;
|
||||
updateSelection(selectionStart, trimmedEnd);
|
||||
setStatus('Clip end moved to where the dialogue ends. Reset restores the subtitle timing.');
|
||||
}
|
||||
|
||||
function queueWaveformLoad(delayMs = 0): void {
|
||||
if (waveformTimer !== null) clearTimeout(waveformTimer);
|
||||
waveformSequence += 1;
|
||||
@@ -443,6 +532,7 @@ export function createMediaTimingReviewModal(
|
||||
});
|
||||
selectionStart = nextSelection.start;
|
||||
selectionEnd = nextSelection.end;
|
||||
trailingTrimPending = false;
|
||||
if (previewPlaying || previewRequest.isInFlight()) stopPreview();
|
||||
setStatus('');
|
||||
renderSelection();
|
||||
@@ -704,6 +794,7 @@ export function createMediaTimingReviewModal(
|
||||
nextCount = 0;
|
||||
startPadSeconds = Math.max(0, nextPayload.originalStartTime - nextPayload.selectionStartTime);
|
||||
endPadSeconds = Math.max(0, nextPayload.selectionEndTime - nextPayload.originalEndTime);
|
||||
trailingTrimPending = true;
|
||||
resolveInFlight = false;
|
||||
setPreviewPlaying(false);
|
||||
ctx.dom.mediaTimingReviewKind.textContent =
|
||||
@@ -851,6 +942,7 @@ export function createMediaTimingReviewModal(
|
||||
|
||||
return {
|
||||
openMediaTimingReviewModal,
|
||||
handlePreviewEnded,
|
||||
requestCancel,
|
||||
handleMediaTimingReviewKeydown,
|
||||
wireDomEvents,
|
||||
|
||||
@@ -40,13 +40,19 @@ function createElementStub() {
|
||||
}
|
||||
|
||||
function createListStub() {
|
||||
return {
|
||||
innerHTML: '',
|
||||
const list = {
|
||||
children: [] as unknown[],
|
||||
appendChild(child: unknown) {
|
||||
this.children.push(child);
|
||||
list.children.push(child);
|
||||
},
|
||||
};
|
||||
// The modal clears lists through innerHTML before re-rendering.
|
||||
return Object.defineProperty(list, 'innerHTML', {
|
||||
get: () => '',
|
||||
set: () => {
|
||||
list.children.length = 0;
|
||||
},
|
||||
}) as typeof list & { innerHTML: string };
|
||||
}
|
||||
|
||||
function createTabStub(active: boolean) {
|
||||
@@ -118,6 +124,7 @@ function createModalHarness(
|
||||
files: TsukihimeSubtitleFile[],
|
||||
options: {
|
||||
secondaryLanguages?: string[];
|
||||
secondaryLanguagesGate?: Promise<void>;
|
||||
downloadFile?: (query: unknown) => Promise<unknown>;
|
||||
listFiles?: (entryId: number) => Promise<unknown>;
|
||||
searchEntries?: (query: unknown) => Promise<unknown>;
|
||||
@@ -138,7 +145,10 @@ function createModalHarness(
|
||||
if (options.downloadFile) return options.downloadFile(query);
|
||||
return { ok: true, path: '/tmp/subtitles/episode01.en.ass' };
|
||||
},
|
||||
tsukihimeGetSecondaryLanguages: async () => options.secondaryLanguages ?? ['en', 'eng'],
|
||||
tsukihimeGetSecondaryLanguages: async () => {
|
||||
await options.secondaryLanguagesGate;
|
||||
return options.secondaryLanguages ?? ['en', 'eng'];
|
||||
},
|
||||
tsukihimeListFiles: async ({ entryId }: { entryId: number }) =>
|
||||
options.listFiles ? options.listFiles(entryId) : { ok: true, data: [] },
|
||||
tsukihimeSearchEntries: async (query: unknown) =>
|
||||
@@ -613,3 +623,202 @@ test('renderFiles omits the size detail when the API does not report one', () =>
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
const ENGLISH_ONLY_ENTRY = {
|
||||
id: 606713,
|
||||
title: 'english only release',
|
||||
timestamp: null,
|
||||
totalSize: null,
|
||||
numFiles: 1,
|
||||
sublangs: ['en'],
|
||||
};
|
||||
|
||||
const MULTI_SUB_ENTRY = {
|
||||
id: 12255,
|
||||
title: 'multi-sub release',
|
||||
timestamp: null,
|
||||
totalSize: null,
|
||||
numFiles: 1,
|
||||
sublangs: ['en-US', 'ja'],
|
||||
};
|
||||
|
||||
const UNLABELED_ENTRY = {
|
||||
id: 12256,
|
||||
title: 'release without langs',
|
||||
timestamp: null,
|
||||
totalSize: null,
|
||||
numFiles: 1,
|
||||
sublangs: [],
|
||||
};
|
||||
|
||||
function visibleEntryTitles(harness: ModalHarness): string[] {
|
||||
return (harness.entriesList.children as Array<{ textContent: string }>).map(
|
||||
(li) => li.textContent,
|
||||
);
|
||||
}
|
||||
|
||||
test('Japanese tab lists only releases that carry Japanese subtitles', async () => {
|
||||
const SECOND_JAPANESE_TRACK: TsukihimeSubtitleFile = {
|
||||
...JAPANESE_TRACK,
|
||||
attachmentId: 1955401,
|
||||
filename: 'episode01.jpn.sdh.ass',
|
||||
};
|
||||
const harness = createModalHarness([], {
|
||||
// Two tracks so the modal does not auto-download a lone match.
|
||||
listFiles: async () => ({ ok: true, data: [JAPANESE_TRACK, SECOND_JAPANESE_TRACK] }),
|
||||
});
|
||||
try {
|
||||
harness.state.currentTsukihimeEntryId = null;
|
||||
harness.state.tsukihimeEntries = [ENGLISH_ONLY_ENTRY, MULTI_SUB_ENTRY, UNLABELED_ENTRY];
|
||||
|
||||
pressKey(harness, 'ArrowRight');
|
||||
assert.deepEqual(visibleEntryTitles(harness), ['multi-sub release']);
|
||||
|
||||
// Enter addresses the visible list, so it must pick the multi-sub release
|
||||
// rather than the hidden first search result.
|
||||
pressKey(harness, 'Enter');
|
||||
await flushAsyncWork();
|
||||
assert.equal(harness.state.currentTsukihimeEntryId, MULTI_SUB_ENTRY.id);
|
||||
assert.equal(harness.status.textContent, 'Select a subtitle track.');
|
||||
|
||||
pressKey(harness, 'ArrowLeft');
|
||||
assert.deepEqual(visibleEntryTitles(harness), [
|
||||
'english only release',
|
||||
'multi-sub release',
|
||||
'release without langs',
|
||||
]);
|
||||
assert.equal(harness.state.currentTsukihimeEntryId, MULTI_SUB_ENTRY.id);
|
||||
assert.equal(harness.state.selectedTsukihimeEntryIndex, 1);
|
||||
} finally {
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('Japanese tab reports when no release carries Japanese subtitles', () => {
|
||||
const harness = createModalHarness([]);
|
||||
try {
|
||||
harness.state.currentTsukihimeEntryId = null;
|
||||
harness.state.tsukihimeEntries = [ENGLISH_ONLY_ENTRY, UNLABELED_ENTRY];
|
||||
|
||||
pressKey(harness, 'ArrowRight');
|
||||
assert.deepEqual(visibleEntryTitles(harness), []);
|
||||
assert.equal(
|
||||
harness.status.textContent,
|
||||
'No releases with Japanese subtitles. Switch to the English tab.',
|
||||
);
|
||||
|
||||
pressKey(harness, 'ArrowLeft');
|
||||
assert.deepEqual(visibleEntryTitles(harness), [
|
||||
'english only release',
|
||||
'release without langs',
|
||||
]);
|
||||
assert.equal(harness.status.textContent, 'Select a release.');
|
||||
} finally {
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('search reports when no release carries the secondary language', async () => {
|
||||
const harness = createModalHarness([], {
|
||||
searchEntries: async () => ({
|
||||
ok: true,
|
||||
data: [{ ...MULTI_SUB_ENTRY, sublangs: ['ja'] }],
|
||||
}),
|
||||
});
|
||||
try {
|
||||
harness.state.currentTsukihimeEntryId = null;
|
||||
harness.titleInput.value = 'Futsutsuka na Akujo';
|
||||
|
||||
pressKey(harness, 'Enter');
|
||||
await flushAsyncWork();
|
||||
assert.deepEqual(visibleEntryTitles(harness), []);
|
||||
assert.equal(
|
||||
harness.status.textContent,
|
||||
'No releases with English subtitles. Switch to the Japanese tab.',
|
||||
);
|
||||
|
||||
pressKey(harness, 'ArrowRight');
|
||||
assert.deepEqual(visibleEntryTitles(harness), ['multi-sub release']);
|
||||
} finally {
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('switching to a tab that hides the selected release clears its tracks', () => {
|
||||
const harness = createModalHarness([ENGLISH_TRACK, JAPANESE_TRACK]);
|
||||
try {
|
||||
harness.state.tsukihimeEntries = [ENGLISH_ONLY_ENTRY, MULTI_SUB_ENTRY];
|
||||
|
||||
pressKey(harness, 'ArrowRight');
|
||||
assert.equal(harness.state.currentTsukihimeEntryId, null);
|
||||
assert.deepEqual(harness.state.tsukihimeFiles, []);
|
||||
assert.deepEqual(visibleEntryTitles(harness), ['multi-sub release']);
|
||||
assert.equal(harness.status.textContent, 'Select a release.');
|
||||
} finally {
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('a search waits for the configured secondary languages before filtering', async () => {
|
||||
let openGate!: () => void;
|
||||
const harness = createModalHarness([], {
|
||||
secondaryLanguages: ['de'],
|
||||
secondaryLanguagesGate: new Promise<void>((resolve) => {
|
||||
openGate = resolve;
|
||||
}),
|
||||
searchEntries: async () => ({
|
||||
ok: true,
|
||||
data: [{ ...MULTI_SUB_ENTRY, title: 'german release', sublangs: ['de'] }],
|
||||
}),
|
||||
});
|
||||
try {
|
||||
harness.state.tsukihimeModalOpen = false;
|
||||
harness.modal.openTsukihimeModal();
|
||||
harness.titleInput.value = 'Futsutsuka na Akujo';
|
||||
|
||||
// Searching before the config arrives must not filter against the English
|
||||
// fallback, which would hide this German-only release.
|
||||
pressKey(harness, 'Enter');
|
||||
await flushAsyncWork();
|
||||
assert.deepEqual(visibleEntryTitles(harness), []);
|
||||
|
||||
openGate();
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.deepEqual(visibleEntryTitles(harness), ['german release']);
|
||||
} finally {
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('a search from a prior modal session cannot repopulate a reopened modal', async () => {
|
||||
let openGate!: () => void;
|
||||
const harness = createModalHarness([], {
|
||||
secondaryLanguagesGate: new Promise<void>((resolve) => {
|
||||
openGate = resolve;
|
||||
}),
|
||||
searchEntries: async () => ({ ok: true, data: [MULTI_SUB_ENTRY] }),
|
||||
});
|
||||
try {
|
||||
harness.state.tsukihimeModalOpen = false;
|
||||
harness.modal.openTsukihimeModal();
|
||||
harness.titleInput.value = 'Futsutsuka na Akujo';
|
||||
|
||||
// The search parks on the language config, then the user closes and
|
||||
// reopens the modal before it resolves.
|
||||
pressKey(harness, 'Enter');
|
||||
harness.modal.closeTsukihimeModal();
|
||||
harness.modal.openTsukihimeModal();
|
||||
await flushAsyncWork();
|
||||
harness.status.textContent = 'Fresh modal session';
|
||||
|
||||
openGate();
|
||||
await flushAsyncWork();
|
||||
|
||||
assert.deepEqual(harness.state.tsukihimeEntries, []);
|
||||
assert.deepEqual(visibleEntryTitles(harness), []);
|
||||
assert.equal(harness.status.textContent, 'Fresh modal session');
|
||||
} finally {
|
||||
harness.restoreGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -41,7 +41,13 @@ export function createTsukihimeModal(
|
||||
|
||||
// Defaults to English until the configured secondary languages arrive.
|
||||
let secondaryLanguages: string[] = ['en'];
|
||||
// Both tab filters read the configured languages, so a search must wait for
|
||||
// them rather than filtering against the English fallback.
|
||||
let secondaryLanguagesReady: Promise<void> = Promise.resolve();
|
||||
let activeDownloadToken = 0;
|
||||
// Bumped by every new search and by closing the modal, so results that
|
||||
// arrive late cannot repopulate a reopened modal or a newer search.
|
||||
let activeSearchToken = 0;
|
||||
|
||||
function secondaryTabLabel(): string {
|
||||
return describeTsukihimeTabLanguages(secondaryLanguages);
|
||||
@@ -61,6 +67,47 @@ export function createTsukihimeModal(
|
||||
);
|
||||
}
|
||||
|
||||
// Releases are filtered by the languages the search index reports for
|
||||
// them. Most releases carry no Japanese track, so the primary tab hides
|
||||
// them outright. A release with no language data cannot be classified and
|
||||
// stays on the secondary tab, mirroring how unlabeled tracks are handled.
|
||||
function entryMatchesTab(entry: TsukihimeEntry, tab: 'secondary' | 'primary'): boolean {
|
||||
if (tab === 'primary') {
|
||||
return entry.sublangs.some((lang) => normalizeTsukihimeLangCode(lang) === 'ja');
|
||||
}
|
||||
if (entry.sublangs.length === 0) return true;
|
||||
return entry.sublangs.some(
|
||||
(lang) =>
|
||||
normalizeTsukihimeLangCode(lang) !== 'ja' &&
|
||||
tsukihimeTrackMatchesLanguages(lang, secondaryLanguages),
|
||||
);
|
||||
}
|
||||
|
||||
function getVisibleEntries(): TsukihimeEntry[] {
|
||||
return ctx.state.tsukihimeEntries.filter((entry) =>
|
||||
entryMatchesTab(entry, ctx.state.tsukihimeActiveTab),
|
||||
);
|
||||
}
|
||||
|
||||
function describeEmptyReleases(): string {
|
||||
const otherTab = ctx.state.tsukihimeActiveTab === 'primary' ? 'secondary' : 'primary';
|
||||
const otherTabHasReleases = ctx.state.tsukihimeEntries.some((entry) =>
|
||||
entryMatchesTab(entry, otherTab),
|
||||
);
|
||||
const language = ctx.state.tsukihimeActiveTab === 'primary' ? 'Japanese' : secondaryTabLabel();
|
||||
const otherLabel = otherTab === 'primary' ? 'Japanese' : secondaryTabLabel();
|
||||
return otherTabHasReleases
|
||||
? `No releases with ${language} subtitles. Switch to the ${otherLabel} tab.`
|
||||
: `No releases with ${language} subtitles.`;
|
||||
}
|
||||
|
||||
function clearFiles(): void {
|
||||
ctx.state.tsukihimeFiles = [];
|
||||
ctx.state.selectedTsukihimeFileIndex = 0;
|
||||
ctx.dom.tsukihimeFilesList.innerHTML = '';
|
||||
ctx.dom.tsukihimeFilesSection.classList.add('hidden');
|
||||
}
|
||||
|
||||
function renderTabs(): void {
|
||||
const primaryActive = ctx.state.tsukihimeActiveTab === 'primary';
|
||||
ctx.dom.tsukihimeTabSecondaryButton.setAttribute(
|
||||
@@ -98,12 +145,37 @@ export function createTsukihimeModal(
|
||||
ctx.state.selectedTsukihimeFileIndex = 0;
|
||||
renderTabs();
|
||||
|
||||
if (ctx.state.tsukihimeFiles.length === 0) return;
|
||||
renderFiles();
|
||||
if (getVisibleFiles().length === 0) {
|
||||
setTsukihimeStatus(describeEmptyTab());
|
||||
} else {
|
||||
setTsukihimeStatus('Select a subtitle track.');
|
||||
const currentEntry = ctx.state.tsukihimeEntries.find(
|
||||
(entry) => entry.id === ctx.state.currentTsukihimeEntryId,
|
||||
);
|
||||
if (currentEntry && !entryMatchesTab(currentEntry, tab)) {
|
||||
// The selected release is hidden on this tab; drop its tracks so the
|
||||
// list matches what the tab claims to show.
|
||||
ctx.state.currentTsukihimeEntryId = null;
|
||||
ctx.state.selectedTsukihimeEntryIndex = 0;
|
||||
clearFiles();
|
||||
renderEntries();
|
||||
setTsukihimeStatus(
|
||||
getVisibleEntries().length === 0 ? describeEmptyReleases() : 'Select a release.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const visibleEntries = getVisibleEntries();
|
||||
ctx.state.selectedTsukihimeEntryIndex = currentEntry ? visibleEntries.indexOf(currentEntry) : 0;
|
||||
renderEntries();
|
||||
|
||||
if (ctx.state.tsukihimeFiles.length > 0) {
|
||||
renderFiles();
|
||||
setTsukihimeStatus(
|
||||
getVisibleFiles().length === 0 ? describeEmptyTab() : 'Select a subtitle track.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!currentEntry && ctx.state.tsukihimeEntries.length > 0) {
|
||||
setTsukihimeStatus(
|
||||
visibleEntries.length === 0 ? describeEmptyReleases() : 'Select a release.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,13 +193,14 @@ export function createTsukihimeModal(
|
||||
|
||||
function renderEntries(): void {
|
||||
ctx.dom.tsukihimeEntriesList.innerHTML = '';
|
||||
if (ctx.state.tsukihimeEntries.length === 0) {
|
||||
const visibleEntries = getVisibleEntries();
|
||||
if (visibleEntries.length === 0) {
|
||||
ctx.dom.tsukihimeEntriesSection.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.dom.tsukihimeEntriesSection.classList.remove('hidden');
|
||||
ctx.state.tsukihimeEntries.forEach((entry, index) => {
|
||||
visibleEntries.forEach((entry, index) => {
|
||||
const li = document.createElement('li');
|
||||
li.textContent = entry.title;
|
||||
|
||||
@@ -210,11 +283,15 @@ export function createTsukihimeModal(
|
||||
return;
|
||||
}
|
||||
|
||||
const searchToken = ++activeSearchToken;
|
||||
resetTsukihimeLists();
|
||||
setTsukihimeStatus('Searching TsukiHime...');
|
||||
await secondaryLanguagesReady;
|
||||
if (searchToken !== activeSearchToken) return;
|
||||
|
||||
const response: TsukihimeApiResponse<TsukihimeEntry[]> =
|
||||
await window.electronAPI.tsukihimeSearchEntries({ query });
|
||||
if (searchToken !== activeSearchToken) return;
|
||||
if (!response.ok) {
|
||||
setTsukihimeStatus(response.error.error, true);
|
||||
return;
|
||||
@@ -228,20 +305,22 @@ export function createTsukihimeModal(
|
||||
return;
|
||||
}
|
||||
|
||||
const visibleEntries = getVisibleEntries();
|
||||
if (visibleEntries.length === 0) {
|
||||
setTsukihimeStatus(describeEmptyReleases());
|
||||
return;
|
||||
}
|
||||
|
||||
setTsukihimeStatus('Select a release.');
|
||||
renderEntries();
|
||||
if (ctx.state.tsukihimeEntries.length === 1) {
|
||||
if (visibleEntries.length === 1) {
|
||||
selectEntry(0);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFiles(entryId: number): Promise<void> {
|
||||
setTsukihimeStatus('Loading subtitle tracks...');
|
||||
ctx.state.tsukihimeFiles = [];
|
||||
ctx.state.selectedTsukihimeFileIndex = 0;
|
||||
|
||||
ctx.dom.tsukihimeFilesList.innerHTML = '';
|
||||
ctx.dom.tsukihimeFilesSection.classList.add('hidden');
|
||||
clearFiles();
|
||||
|
||||
const response: TsukihimeApiResponse<TsukihimeSubtitleFile[]> =
|
||||
await window.electronAPI.tsukihimeListFiles({ entryId });
|
||||
@@ -279,11 +358,14 @@ export function createTsukihimeModal(
|
||||
}
|
||||
}
|
||||
|
||||
// `index` addresses the entries visible on the active tab, not the full
|
||||
// search result list.
|
||||
function selectEntry(index: number): void {
|
||||
if (index < 0 || index >= ctx.state.tsukihimeEntries.length) return;
|
||||
const visibleEntries = getVisibleEntries();
|
||||
if (index < 0 || index >= visibleEntries.length) return;
|
||||
|
||||
ctx.state.selectedTsukihimeEntryIndex = index;
|
||||
ctx.state.currentTsukihimeEntryId = ctx.state.tsukihimeEntries[index]!.id;
|
||||
ctx.state.currentTsukihimeEntryId = visibleEntries[index]!.id;
|
||||
renderEntries();
|
||||
|
||||
if (ctx.state.currentTsukihimeEntryId !== null) {
|
||||
@@ -363,16 +445,15 @@ export function createTsukihimeModal(
|
||||
resetTsukihimeLists();
|
||||
renderTabs();
|
||||
|
||||
const secondaryLanguagesReady = loadSecondaryLanguages();
|
||||
secondaryLanguagesReady = loadSecondaryLanguages();
|
||||
|
||||
window.electronAPI
|
||||
.getJimakuMediaInfo()
|
||||
.then(async (info: JimakuMediaInfo) => {
|
||||
.then((info: JimakuMediaInfo) => {
|
||||
ctx.dom.tsukihimeTitleInput.value = info.title || '';
|
||||
ctx.dom.tsukihimeEpisodeInput.value = info.episode ? String(info.episode) : '';
|
||||
|
||||
if (info.confidence === 'high' && info.title && info.episode) {
|
||||
await secondaryLanguagesReady;
|
||||
void performTsukihimeSearch();
|
||||
} else if (info.title) {
|
||||
setTsukihimeStatus('Check title/episode and press Search.');
|
||||
@@ -389,6 +470,7 @@ export function createTsukihimeModal(
|
||||
if (!ctx.state.tsukihimeModalOpen) return;
|
||||
|
||||
activeDownloadToken += 1;
|
||||
activeSearchToken += 1;
|
||||
ctx.state.tsukihimeModalOpen = false;
|
||||
options.syncSettingsModalSubtitleSuppression();
|
||||
ctx.dom.tsukihimeModal.classList.add('hidden');
|
||||
@@ -438,9 +520,9 @@ export function createTsukihimeModal(
|
||||
ctx.state.selectedTsukihimeFileIndex + 1,
|
||||
);
|
||||
renderFiles();
|
||||
} else if (ctx.state.tsukihimeEntries.length > 0) {
|
||||
} else if (getVisibleEntries().length > 0) {
|
||||
ctx.state.selectedTsukihimeEntryIndex = Math.min(
|
||||
ctx.state.tsukihimeEntries.length - 1,
|
||||
getVisibleEntries().length - 1,
|
||||
ctx.state.selectedTsukihimeEntryIndex + 1,
|
||||
);
|
||||
renderEntries();
|
||||
@@ -456,7 +538,7 @@ export function createTsukihimeModal(
|
||||
ctx.state.selectedTsukihimeFileIndex - 1,
|
||||
);
|
||||
renderFiles();
|
||||
} else if (ctx.state.tsukihimeEntries.length > 0) {
|
||||
} else if (getVisibleEntries().length > 0) {
|
||||
ctx.state.selectedTsukihimeEntryIndex = Math.max(
|
||||
0,
|
||||
ctx.state.selectedTsukihimeEntryIndex - 1,
|
||||
@@ -470,7 +552,7 @@ export function createTsukihimeModal(
|
||||
e.preventDefault();
|
||||
if (getVisibleFiles().length > 0) {
|
||||
void selectFile(ctx.state.selectedTsukihimeFileIndex);
|
||||
} else if (ctx.state.tsukihimeEntries.length > 0) {
|
||||
} else if (getVisibleEntries().length > 0) {
|
||||
selectEntry(ctx.state.selectedTsukihimeEntryIndex);
|
||||
} else {
|
||||
void performTsukihimeSearch();
|
||||
|
||||
@@ -591,6 +591,11 @@ function registerModalOpenHandlers(): void {
|
||||
mediaTimingReviewModal.openMediaTimingReviewModal(payload);
|
||||
});
|
||||
});
|
||||
window.electronAPI.onMediaTimingReviewPreviewEnded((reviewId) => {
|
||||
runGuarded('media-timing-review:preview-ended', () => {
|
||||
mediaTimingReviewModal.handlePreviewEnded(reviewId);
|
||||
});
|
||||
});
|
||||
window.electronAPI.onOpenPlaylistBrowser(() => {
|
||||
runGuardedAsync('playlist-browser:open', async () => {
|
||||
await playlistBrowserModal.openPlaylistBrowserModal();
|
||||
|
||||
@@ -148,6 +148,7 @@ export const IPC_CHANNELS = {
|
||||
tsukihimeOpen: 'tsukihime:open',
|
||||
youtubePickerOpen: 'youtube:picker-open',
|
||||
mediaTimingReviewOpen: 'media-timing-review:open',
|
||||
mediaTimingReviewPreviewEnded: 'media-timing-review:preview-ended',
|
||||
youtubePickerCancel: 'youtube:picker-cancel',
|
||||
playlistBrowserOpen: 'playlist-browser:open',
|
||||
sessionNumericSelectionStart: 'session:numeric-selection-start',
|
||||
|
||||
@@ -523,6 +523,7 @@ export interface ElectronAPI {
|
||||
onOpenTsukihime: (callback: () => void) => void;
|
||||
onOpenYoutubeTrackPicker: (callback: (payload: YoutubePickerOpenPayload) => void) => void;
|
||||
onOpenMediaTimingReview: (callback: (payload: MediaTimingReviewOpenPayload) => void) => void;
|
||||
onMediaTimingReviewPreviewEnded: (callback: (reviewId: string) => void) => void;
|
||||
previewMediaTimingReview: (
|
||||
request: MediaTimingReviewPreviewRequest,
|
||||
) => Promise<MediaTimingReviewActionResult>;
|
||||
|
||||
Reference in New Issue
Block a user