mirror of
https://github.com/ksyasuda/SubMiner.git
synced 2026-11-23 04:46:08 -08:00
feat(aniskip): detect intros and outros from file chapters and AniSkip v2 (#334)
This commit is contained in:
1 parent
ee52664655
commit
ac3ceab856
16 files changed
+1077
-286
No files matched your search
@@ -1118,7 +1118,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
aniskipEnabled: configService.getConfig().mpv.aniskipEnabled,
|
||||
aniskipButtonKey: configService.getConfig().mpv.aniskipButtonKey,
|
||||
}),
|
||||
resolveMetadataForFile: (mediaPath) => resolveAniSkipMetadataForFile(mediaPath),
|
||||
resolveMetadataForFile: (mediaPath, episodeLength) =>
|
||||
resolveAniSkipMetadataForFile(mediaPath, { episodeLength }),
|
||||
sendMpvCommand: (command) => {
|
||||
appState.mpvClient?.send({ command });
|
||||
},
|
||||
@@ -1163,6 +1164,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
|
||||
});
|
||||
client.on('connection-change', aniSkipRuntime.handleConnectionChange);
|
||||
client.on('media-path-change', aniSkipRuntime.handleMediaPathChange);
|
||||
client.on('duration-change', aniSkipRuntime.handleDurationChange);
|
||||
client.on('time-pos-change', aniSkipRuntime.handleTimePosChange);
|
||||
client.on('client-message', aniSkipRuntime.handleClientMessage);
|
||||
deps.getPluginHost().attachMpvClient(client);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyChapterSkipIntervals } from './aniskip-chapters';
|
||||
|
||||
const DURATION = 1440;
|
||||
|
||||
function chapters(...entries: Array<[number, string]>) {
|
||||
return entries.map(([time, title]) => ({ time, title }));
|
||||
}
|
||||
|
||||
test('finds named openings and endings case-insensitively', () => {
|
||||
const result = classifyChapterSkipIntervals(
|
||||
chapters([0, 'Prologue'], [95, 'OPENING'], [185, 'Part A'], [1310, 'Ending'], [1400, 'Next']),
|
||||
DURATION,
|
||||
);
|
||||
assert.deepEqual(result, {
|
||||
intro: { start: 95, end: 185 },
|
||||
outro: { start: 1310, end: 1400 },
|
||||
});
|
||||
});
|
||||
|
||||
test('matches short OP/ED titles but not words that merely start with them', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Op'], [90, 'Episode'], [1350, 'ED']), DURATION),
|
||||
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(
|
||||
chapters([0, 'OP "Song Title"'], [90, 'Episode'], [1350, 'ED "Song Title"']),
|
||||
DURATION,
|
||||
),
|
||||
{ intro: { start: 0, end: 90 }, outro: { start: 1350, end: 1440 } },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Operation'], [500, 'Editing']), DURATION),
|
||||
{ intro: null, outro: null },
|
||||
);
|
||||
});
|
||||
|
||||
test('recognises Japanese chapter names', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(
|
||||
chapters([0, 'アバン'], [60, 'オープニング'], [150, '本編'], [1330, 'エンディング']),
|
||||
DURATION,
|
||||
),
|
||||
{ intro: { start: 60, end: 150 }, outro: { start: 1330, end: 1440 } },
|
||||
);
|
||||
});
|
||||
|
||||
test('accepts outro and credits names, with bare "Credits" only in the second half', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Outro']), DURATION).outro,
|
||||
{ start: 1350, end: 1440 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Closing Credits']), DURATION)
|
||||
.outro,
|
||||
{ start: 1350, end: 1440 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Credits'], [90, 'Episode']), DURATION).outro,
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Episode'], [1350, 'Credits']), DURATION).outro,
|
||||
{ start: 1350, end: 1440 },
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to song-length heuristics when the file has at least three chapters', () => {
|
||||
const result = classifyChapterSkipIntervals(
|
||||
chapters(
|
||||
[0, 'Chapter 1'],
|
||||
[60, 'Chapter 2'], // 60 s long, in the first 30%
|
||||
[120, 'Chapter 3'], // 88 s long, nearest 90 s
|
||||
[208, 'Chapter 4'],
|
||||
[1100, 'Chapter 5'], // starts after 70% but 230 s long
|
||||
[1330, 'Chapter 6'], // first song-length chapter after 70%
|
||||
[1420, 'Chapter 7'],
|
||||
),
|
||||
DURATION,
|
||||
);
|
||||
assert.deepEqual(result, {
|
||||
intro: { start: 120, end: 208 },
|
||||
outro: { start: 1330, end: 1420 },
|
||||
});
|
||||
});
|
||||
|
||||
test('skips heuristics for files with fewer than three chapters', () => {
|
||||
assert.deepEqual(
|
||||
classifyChapterSkipIntervals(chapters([0, 'Chapter 1'], [1350, 'Chapter 2']), DURATION),
|
||||
{ intro: null, outro: null },
|
||||
);
|
||||
});
|
||||
|
||||
test("ignores SubMiner's own AniSkip marker chapters", () => {
|
||||
const result = classifyChapterSkipIntervals(
|
||||
chapters(
|
||||
[0, 'Episode'],
|
||||
[10, 'AniSkip Intro Start'],
|
||||
[100, 'AniSkip Intro End'],
|
||||
[1330, 'AniSkip Outro Start'],
|
||||
[1420, 'AniSkip Outro End'],
|
||||
),
|
||||
DURATION,
|
||||
);
|
||||
assert.deepEqual(result, { intro: null, outro: null });
|
||||
});
|
||||
|
||||
test('returns nothing without a usable duration or chapter list', () => {
|
||||
assert.deepEqual(classifyChapterSkipIntervals(chapters([0, 'Opening'], [90, 'A']), 0), {
|
||||
intro: null,
|
||||
outro: null,
|
||||
});
|
||||
assert.deepEqual(classifyChapterSkipIntervals(null, DURATION), { intro: null, outro: null });
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
/** A skippable time range in seconds. */
|
||||
export interface SkipInterval {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export interface ChapterSkipIntervals {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
}
|
||||
|
||||
/** Prefix of the marker chapters SubMiner writes; never treated as the file's own chapters. */
|
||||
export const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
|
||||
|
||||
interface Chapter {
|
||||
title: string;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
const MIN_HEURISTIC_CHAPTERS = 3;
|
||||
const MIN_SONG_SECONDS = 55;
|
||||
const MAX_SONG_SECONDS = 150;
|
||||
const TYPICAL_OPENING_SECONDS = 90;
|
||||
|
||||
function isSongLength(chapter: Chapter): boolean {
|
||||
const length = chapter.end - chapter.start;
|
||||
return length >= MIN_SONG_SECONDS && length <= MAX_SONG_SECONDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns mpv's `chapter-list` (entries with `time` and `title`) into sorted
|
||||
* chapters with an end time (the next chapter's start, or the duration),
|
||||
* dropping SubMiner's own AniSkip marker chapters.
|
||||
*/
|
||||
function toChapters(chapterList: unknown, duration: number): Chapter[] {
|
||||
if (!Array.isArray(chapterList)) return [];
|
||||
const starts: Array<{ title: string; start: number }> = [];
|
||||
for (const entry of chapterList) {
|
||||
if (typeof entry !== 'object' || entry === null) continue;
|
||||
const { time, title } = entry as { time?: unknown; title?: unknown };
|
||||
if (typeof time !== 'number' || !Number.isFinite(time) || time < 0 || time >= duration) {
|
||||
continue;
|
||||
}
|
||||
const text = typeof title === 'string' ? title : '';
|
||||
if (text.startsWith(ANISKIP_CHAPTER_PREFIX)) continue;
|
||||
starts.push({ title: text, start: time });
|
||||
}
|
||||
starts.sort((a, b) => a.start - b.start);
|
||||
return starts.map((chapter, index) => ({
|
||||
...chapter,
|
||||
end: starts[index + 1]?.start ?? duration,
|
||||
}));
|
||||
}
|
||||
|
||||
function isNamedOpening(chapter: Chapter): boolean {
|
||||
const title = chapter.title.trim().toLowerCase();
|
||||
return (
|
||||
title.includes('opening') ||
|
||||
title === 'op' ||
|
||||
title.startsWith('op ') ||
|
||||
chapter.title.includes('オープニング')
|
||||
);
|
||||
}
|
||||
|
||||
function isNamedEnding(chapter: Chapter, duration: number): boolean {
|
||||
const title = chapter.title.trim().toLowerCase();
|
||||
return (
|
||||
title.includes('ending') ||
|
||||
title === 'ed' ||
|
||||
title === 'outro' ||
|
||||
title === 'end credits' ||
|
||||
title === 'closing credits' ||
|
||||
(title === 'credits' && chapter.start > duration * 0.5) ||
|
||||
title.startsWith('ed ') ||
|
||||
chapter.title.includes('エンディング')
|
||||
);
|
||||
}
|
||||
|
||||
function findOpening(chapters: Chapter[], duration: number): Chapter | null {
|
||||
const named = chapters.find(isNamedOpening);
|
||||
if (named) return named;
|
||||
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
|
||||
let best: Chapter | null = null;
|
||||
for (const chapter of chapters) {
|
||||
if (chapter.start >= duration * 0.3 || !isSongLength(chapter)) continue;
|
||||
const distance = Math.abs(chapter.end - chapter.start - TYPICAL_OPENING_SECONDS);
|
||||
if (!best || distance < Math.abs(best.end - best.start - TYPICAL_OPENING_SECONDS)) {
|
||||
best = chapter;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function findEnding(chapters: Chapter[], duration: number): Chapter | null {
|
||||
const named = chapters.find((chapter) => isNamedEnding(chapter, duration));
|
||||
if (named) return named;
|
||||
if (chapters.length < MIN_HEURISTIC_CHAPTERS) return null;
|
||||
return (
|
||||
chapters.find((chapter) => chapter.start > duration * 0.7 && isSongLength(chapter)) ?? null
|
||||
);
|
||||
}
|
||||
|
||||
function toInterval(chapter: Chapter | null): SkipInterval | null {
|
||||
return chapter && chapter.end > chapter.start ? { start: chapter.start, end: chapter.end } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the opening and ending in a file's own chapters: by name first
|
||||
* ("Opening", "OP", "ED", "Credits", オープニング, ...), else by length and
|
||||
* position when the file has at least three chapters. Rules follow Telly's
|
||||
* `media.rs` opening()/ending().
|
||||
*/
|
||||
export function classifyChapterSkipIntervals(
|
||||
chapterList: unknown,
|
||||
duration: number,
|
||||
): ChapterSkipIntervals {
|
||||
if (!Number.isFinite(duration) || duration <= 0) return { intro: null, outro: null };
|
||||
const chapters = toChapters(chapterList, duration);
|
||||
return {
|
||||
intro: toInterval(findOpening(chapters, duration)),
|
||||
outro: toInterval(findEnding(chapters, duration)),
|
||||
};
|
||||
}
|
||||
@@ -3,17 +3,21 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
inferAniSkipMetadataForFile,
|
||||
parseAniSkipGuessitJson,
|
||||
parseAniSkipPayload,
|
||||
resolveAniSkipMetadataForFile,
|
||||
} from './aniskip-metadata';
|
||||
|
||||
function makeMockResponse(payload: unknown): Response {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => payload,
|
||||
} as Response;
|
||||
const LOOKUP = { episodeLength: 1440 };
|
||||
|
||||
function makeMockResponse(payload: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
const MAL_MY_SHOW = { categories: [{ items: [{ id: '1234', name: 'My Show' }] }] };
|
||||
|
||||
function normalizeFetchInput(input: string | URL | Request): string {
|
||||
if (typeof input === 'string') return input;
|
||||
if (input instanceof URL) return input.toString();
|
||||
@@ -46,8 +50,8 @@ test('parseAniSkipGuessitJson extracts title season and episode', () => {
|
||||
episode: 7,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
});
|
||||
});
|
||||
@@ -68,8 +72,8 @@ test('parseAniSkipGuessitJson prefers series over episode title', () => {
|
||||
episode: 10,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
});
|
||||
});
|
||||
@@ -111,10 +115,58 @@ test('inferAniSkipMetadataForFile handles release-group filename with trailing q
|
||||
assert.equal(parsed.source, 'fallback');
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async () => {
|
||||
test('parseAniSkipPayload reads op and ed from a v2 response', () => {
|
||||
// Shape captured from api.aniskip.com/v2 on 2026-11-22.
|
||||
const parsed = parseAniSkipPayload({
|
||||
found: true,
|
||||
results: [
|
||||
{
|
||||
interval: { startTime: 310.571, endTime: 400.571 },
|
||||
skipType: 'op',
|
||||
skipId: 'd4f34b6d-0547-4438-ac93-b25b577eddd5',
|
||||
episodeLength: 1443.984,
|
||||
},
|
||||
{
|
||||
interval: { startTime: 1396.006, endTime: 1434 },
|
||||
skipType: 'ed',
|
||||
skipId: '5751c57a-2bcd-4dd9-be93-58e6af0f8c81',
|
||||
episodeLength: 1434.985,
|
||||
},
|
||||
],
|
||||
message: 'Successfully found skip times',
|
||||
statusCode: 200,
|
||||
});
|
||||
assert.deepEqual(parsed, {
|
||||
intro: { start: 310.571, end: 400.571 },
|
||||
outro: { start: 1396.006, end: 1434 },
|
||||
});
|
||||
});
|
||||
|
||||
test('parseAniSkipPayload ignores invalid intervals and not-found responses', () => {
|
||||
assert.deepEqual(
|
||||
parseAniSkipPayload({
|
||||
found: true,
|
||||
results: [
|
||||
{ skipType: 'op', interval: { startTime: 50, endTime: 20 } },
|
||||
{ skipType: 'op', interval: { startTime: 0, endTime: 89.5 } },
|
||||
{ skipType: 'recap', interval: { startTime: 0, endTime: 30 } },
|
||||
],
|
||||
}),
|
||||
{ intro: { start: 0, end: 89.5 }, outro: null },
|
||||
);
|
||||
assert.deepEqual(parseAniSkipPayload({ found: false, results: [] }), {
|
||||
intro: null,
|
||||
outro: null,
|
||||
});
|
||||
assert.deepEqual(parseAniSkipPayload(null), { intro: null, outro: null });
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile queries AniSkip v2 with the episode length', async () => {
|
||||
const requested: string[] = [];
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
requested.push(url);
|
||||
if (url.includes('myanimelist.net/search/prefix.json')) {
|
||||
return makeMockResponse({
|
||||
categories: [
|
||||
@@ -127,48 +179,82 @@ test('resolveAniSkipMetadataForFile resolves MAL id and intro payload', async ()
|
||||
],
|
||||
});
|
||||
}
|
||||
if (url.includes('api.aniskip.com/v1/skip-times/1234/7')) {
|
||||
if (url.includes('api.aniskip.com/v2/skip-times/1234/7')) {
|
||||
return makeMockResponse({
|
||||
found: true,
|
||||
results: [{ skip_type: 'op', interval: { start_time: 12.5, end_time: 54.2 } }],
|
||||
results: [
|
||||
{ skipType: 'op', interval: { startTime: 12.5, endTime: 54.2 } },
|
||||
{ skipType: 'ed', interval: { startTime: 1300, endTime: 1390 } },
|
||||
],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected url: ${url}`);
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv');
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/Anime.My.Show.S01E07.mkv', {
|
||||
episodeLength: 1423.4567,
|
||||
});
|
||||
assert.equal(resolved.malId, 1234);
|
||||
assert.equal(resolved.introStart, 12.5);
|
||||
assert.equal(resolved.introEnd, 54.2);
|
||||
assert.deepEqual(resolved.intro, { start: 12.5, end: 54.2 });
|
||||
assert.deepEqual(resolved.outro, { start: 1300, end: 1390 });
|
||||
assert.equal(resolved.lookupStatus, 'ready');
|
||||
assert.equal(resolved.title, 'Anime My Show');
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
requested[1],
|
||||
'https://api.aniskip.com/v2/skip-times/1234/7?types=op&types=ed&episodeLength=1423.457',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile accepts intro payload starting at zero', async () => {
|
||||
test('resolveAniSkipMetadataForFile treats an AniSkip 404 as a definite miss', async () => {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
if (url.includes('myanimelist.net/search/prefix.json')) {
|
||||
return makeMockResponse({
|
||||
categories: [{ items: [{ id: '1234', name: 'My Show' }] }],
|
||||
});
|
||||
}
|
||||
if (url.includes('api.aniskip.com/v1/skip-times/1234/1')) {
|
||||
return makeMockResponse({
|
||||
found: true,
|
||||
results: [{ skip_type: 'op', interval: { start_time: 0, end_time: 89.5 } }],
|
||||
});
|
||||
}
|
||||
throw new Error(`unexpected url: ${url}`);
|
||||
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
|
||||
return makeMockResponse(
|
||||
{ found: false, results: [], message: 'No skip times found', statusCode: 404 },
|
||||
404,
|
||||
);
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E01.mkv');
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E02.mkv', LOOKUP);
|
||||
assert.equal(resolved.malId, 1234);
|
||||
assert.equal(resolved.introStart, 0);
|
||||
assert.equal(resolved.introEnd, 89.5);
|
||||
assert.equal(resolved.lookupStatus, 'ready');
|
||||
assert.equal(resolved.lookupStatus, 'missing_payload');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAniSkipMetadataForFile reports transient failures as lookup_failed', async () => {
|
||||
const failures: Array<[string, () => Promise<Response>]> = [
|
||||
['AniSkip rate limit', async () => makeMockResponse({ statusCode: 429 }, 429)],
|
||||
['AniSkip server error', async () => makeMockResponse({ statusCode: 503 }, 503)],
|
||||
[
|
||||
'network error',
|
||||
async () => {
|
||||
throw new TypeError('fetch failed');
|
||||
},
|
||||
],
|
||||
];
|
||||
for (const [label, failAniSkip] of failures) {
|
||||
await withMockFetch(
|
||||
async (input) => {
|
||||
const url = normalizeFetchInput(input);
|
||||
if (url.includes('myanimelist.net')) return makeMockResponse(MAL_MY_SHOW);
|
||||
return failAniSkip();
|
||||
},
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.lookupStatus, 'lookup_failed', label);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await withMockFetch(
|
||||
async () => makeMockResponse({}, 429),
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/My.Show.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.lookupStatus, 'lookup_failed', 'MAL rate limit');
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -177,7 +263,7 @@ test('resolveAniSkipMetadataForFile emits missing_mal_id when MAL search misses'
|
||||
await withMockFetch(
|
||||
async () => makeMockResponse({ categories: [] }),
|
||||
async () => {
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv');
|
||||
const resolved = await resolveAniSkipMetadataForFile('/media/NopeShow.S01E03.mkv', LOOKUP);
|
||||
assert.equal(resolved.malId, null);
|
||||
assert.equal(resolved.lookupStatus, 'missing_mal_id');
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import type { SkipInterval } from './aniskip-chapters';
|
||||
|
||||
export type AniSkipLookupStatus =
|
||||
| 'ready'
|
||||
@@ -15,11 +16,16 @@ export interface AniSkipMetadata {
|
||||
episode: number | null;
|
||||
source: 'guessit' | 'fallback';
|
||||
malId: number | null;
|
||||
introStart: number | null;
|
||||
introEnd: number | null;
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
lookupStatus?: AniSkipLookupStatus;
|
||||
}
|
||||
|
||||
export interface AniSkipLookupOptions {
|
||||
/** Length of the playing file in seconds; AniSkip v2 uses it to pick times marked on the same cut. */
|
||||
episodeLength: number;
|
||||
}
|
||||
|
||||
interface InferAniSkipDeps {
|
||||
commandExists: (name: string) => boolean;
|
||||
runGuessit: (mediaPath: string) => string | null;
|
||||
@@ -39,12 +45,12 @@ interface MalSearchResponse {
|
||||
}
|
||||
|
||||
interface AniSkipIntervalPayload {
|
||||
start_time?: unknown;
|
||||
end_time?: unknown;
|
||||
startTime?: unknown;
|
||||
endTime?: unknown;
|
||||
}
|
||||
|
||||
interface AniSkipSkipItemPayload {
|
||||
skip_type?: unknown;
|
||||
skipType?: unknown;
|
||||
interval?: unknown;
|
||||
}
|
||||
|
||||
@@ -61,9 +67,12 @@ const ROMAN_SEASON_ALIASES: Record<number, readonly string[]> = {
|
||||
};
|
||||
|
||||
const MAL_PREFIX_API = 'https://myanimelist.net/search/prefix.json?type=anime&keyword=';
|
||||
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v1/skip-times/';
|
||||
const ANISKIP_PAYLOAD_API = 'https://api.aniskip.com/v2/skip-times/';
|
||||
const ANISKIP_USER_AGENT = 'SubMiner/ani-skip';
|
||||
const ANISKIP_FETCH_TIMEOUT_MS = 8000;
|
||||
// AniSkip allows 120 requests a minute; one lookup per file load stays far below that,
|
||||
// but a gap keeps fast playlist skipping from bursting.
|
||||
const ANISKIP_MIN_REQUEST_GAP_MS = 1000;
|
||||
const MAL_MATCH_STOPWORDS = new Set([
|
||||
'the',
|
||||
'this',
|
||||
@@ -261,49 +270,71 @@ function toMalSearchItems(payload: unknown): MalSearchResult[] {
|
||||
return items;
|
||||
}
|
||||
|
||||
function parseAniSkipPayload(payload: unknown): { start: number; end: number } | null {
|
||||
const parsed = payload as AniSkipPayloadResponse;
|
||||
const results = Array.isArray(parsed?.results) ? parsed.results : null;
|
||||
if (!results) return null;
|
||||
|
||||
for (const rawResult of results) {
|
||||
const result = rawResult as AniSkipSkipItemPayload;
|
||||
if (
|
||||
result.skip_type !== 'op' ||
|
||||
typeof result.interval !== 'object' ||
|
||||
result.interval === null
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const interval = result.interval as AniSkipIntervalPayload;
|
||||
const start = toNonNegativeNumber(interval?.start_time);
|
||||
const end = toPositiveNumber(interval?.end_time);
|
||||
if (start !== null && end !== null && end > start) {
|
||||
return { start, end };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
function parseInterval(raw: unknown): SkipInterval | null {
|
||||
if (typeof raw !== 'object' || raw === null) return null;
|
||||
const interval = raw as AniSkipIntervalPayload;
|
||||
const start = toNonNegativeNumber(interval.startTime);
|
||||
const end = toPositiveNumber(interval.endTime);
|
||||
return start !== null && end !== null && end > start ? { start, end } : null;
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string): Promise<T | null> {
|
||||
/** Reads the first valid opening (`op`) and ending (`ed`) from an AniSkip v2 response. */
|
||||
export function parseAniSkipPayload(payload: unknown): {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
} {
|
||||
const parsed = payload as AniSkipPayloadResponse | null;
|
||||
const results = parsed?.found === true && Array.isArray(parsed.results) ? parsed.results : [];
|
||||
let intro: SkipInterval | null = null;
|
||||
let outro: SkipInterval | null = null;
|
||||
for (const rawResult of results) {
|
||||
const result = rawResult as AniSkipSkipItemPayload;
|
||||
if (result.skipType === 'op' && !intro) intro = parseInterval(result.interval);
|
||||
if (result.skipType === 'ed' && !outro) outro = parseInterval(result.interval);
|
||||
}
|
||||
return { intro, outro };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches JSON. A 404 is a definite "nothing here" and returns null; any other
|
||||
* failure (non-OK status, network error, timeout, bad JSON) throws so callers
|
||||
* report a retryable lookup failure instead of caching a miss.
|
||||
*/
|
||||
async function fetchJson(url: string): Promise<unknown> {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
'User-Agent': ANISKIP_USER_AGENT,
|
||||
},
|
||||
signal: AbortSignal.timeout(ANISKIP_FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
try {
|
||||
return (await response.json()) as T;
|
||||
} catch {
|
||||
return null;
|
||||
if (response.status === 404) return null;
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status} from ${new URL(url).host}`);
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
let lastAniSkipRequestAt = 0;
|
||||
let aniSkipRequestQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
/**
|
||||
* Resolves when the caller may send its AniSkip request. Callers are released
|
||||
* one at a time, each at least ANISKIP_MIN_REQUEST_GAP_MS after the previous
|
||||
* release, so timers that fire late cannot release a burst.
|
||||
*/
|
||||
function waitForAniSkipRequestSlot(): Promise<void> {
|
||||
const slot = aniSkipRequestQueue.then(async () => {
|
||||
const waitMs = lastAniSkipRequestAt + ANISKIP_MIN_REQUEST_GAP_MS - Date.now();
|
||||
if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
|
||||
lastAniSkipRequestAt = Date.now();
|
||||
});
|
||||
aniSkipRequestQueue = slot;
|
||||
return slot;
|
||||
}
|
||||
|
||||
async function resolveMalIdFromTitle(title: string, season: number | null): Promise<number | null> {
|
||||
const lookup = season && season > 1 ? `${title} Season ${season}` : title;
|
||||
const payload = await fetchJson<unknown>(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
|
||||
const payload = await fetchJson(`${MAL_PREFIX_API}${encodeURIComponent(lookup)}`);
|
||||
const items = toMalSearchItems(payload);
|
||||
if (!items.length) return null;
|
||||
|
||||
@@ -326,16 +357,17 @@ async function resolveMalIdFromTitle(title: string, season: number | null): Prom
|
||||
return bestMalId;
|
||||
}
|
||||
|
||||
async function fetchAniSkipPayload(
|
||||
async function fetchAniSkipIntervals(
|
||||
malId: number,
|
||||
episode: number,
|
||||
): Promise<{ start: number; end: number } | null> {
|
||||
const payload = await fetchJson<unknown>(
|
||||
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed`,
|
||||
episodeLength: number,
|
||||
): Promise<{ intro: SkipInterval | null; outro: SkipInterval | null }> {
|
||||
await waitForAniSkipRequestSlot();
|
||||
const length = Math.round(episodeLength * 1000) / 1000;
|
||||
const payload = await fetchJson(
|
||||
`${ANISKIP_PAYLOAD_API}${malId}/${episode}?types=op&types=ed&episodeLength=${length}`,
|
||||
);
|
||||
const parsed = payload as AniSkipPayloadResponse;
|
||||
if (!parsed || parsed.found !== true) return null;
|
||||
return parseAniSkipPayload(parsed);
|
||||
return parseAniSkipPayload(payload);
|
||||
}
|
||||
|
||||
function detectEpisodeFromName(baseName: string): number | null {
|
||||
@@ -456,8 +488,8 @@ export function parseAniSkipGuessitJson(stdout: string, mediaPath: string): AniS
|
||||
episode: episodeFromDirect ?? episodeFromList,
|
||||
source: 'guessit',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
} catch {
|
||||
@@ -501,13 +533,20 @@ export function inferAniSkipMetadataForFile(
|
||||
episode: detectEpisodeFromName(baseName),
|
||||
source: 'fallback',
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
intro: null,
|
||||
outro: null,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<AniSkipMetadata> {
|
||||
/**
|
||||
* Resolves a local file's MAL id and AniSkip opening/ending. Statuses other
|
||||
* than `lookup_failed` are definite answers that callers may cache.
|
||||
*/
|
||||
export async function resolveAniSkipMetadataForFile(
|
||||
mediaPath: string,
|
||||
options: AniSkipLookupOptions,
|
||||
): Promise<AniSkipMetadata> {
|
||||
const inferred = inferAniSkipMetadataForFile(mediaPath);
|
||||
if (!inferred.title) {
|
||||
return { ...inferred, lookupStatus: 'lookup_failed' };
|
||||
@@ -516,50 +555,25 @@ export async function resolveAniSkipMetadataForFile(mediaPath: string): Promise<
|
||||
try {
|
||||
const malId = await resolveMalIdFromTitle(inferred.title, inferred.season);
|
||||
if (!malId) {
|
||||
return {
|
||||
...inferred,
|
||||
malId: null,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_mal_id',
|
||||
};
|
||||
return { ...inferred, lookupStatus: 'missing_mal_id' };
|
||||
}
|
||||
|
||||
if (!inferred.episode) {
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_episode',
|
||||
};
|
||||
}
|
||||
|
||||
const payload = await fetchAniSkipPayload(malId, inferred.episode);
|
||||
if (!payload) {
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_payload',
|
||||
};
|
||||
return { ...inferred, malId, lookupStatus: 'missing_episode' };
|
||||
}
|
||||
|
||||
const { intro, outro } = await fetchAniSkipIntervals(
|
||||
malId,
|
||||
inferred.episode,
|
||||
options.episodeLength,
|
||||
);
|
||||
return {
|
||||
...inferred,
|
||||
malId,
|
||||
introStart: payload.start,
|
||||
introEnd: payload.end,
|
||||
lookupStatus: 'ready',
|
||||
intro,
|
||||
outro,
|
||||
lookupStatus: intro || outro ? 'ready' : 'missing_payload',
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
...inferred,
|
||||
malId: inferred.malId,
|
||||
introStart: inferred.introStart,
|
||||
introEnd: inferred.introEnd,
|
||||
lookupStatus: 'lookup_failed',
|
||||
};
|
||||
return { ...inferred, lookupStatus: 'lookup_failed' };
|
||||
}
|
||||
}
|
||||
@@ -10,19 +10,22 @@ function readyMetadata(overrides: Partial<AniSkipMetadata> = {}): AniSkipMetadat
|
||||
episode: 1,
|
||||
source: 'fallback',
|
||||
malId: 1234,
|
||||
introStart: 10,
|
||||
introEnd: 95.5,
|
||||
intro: { start: 10, end: 95.5 },
|
||||
outro: null,
|
||||
lookupStatus: 'ready',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const NO_SKIP_TIMES = { intro: null, outro: null } as const;
|
||||
|
||||
function createHarness(options?: {
|
||||
enabled?: boolean;
|
||||
buttonKey?: string;
|
||||
metadata?: AniSkipMetadata | (() => Promise<AniSkipMetadata>);
|
||||
chapterList?: unknown;
|
||||
playbackFeedback?: boolean;
|
||||
duration?: number | null;
|
||||
}) {
|
||||
const state = {
|
||||
enabled: options?.enabled ?? true,
|
||||
@@ -31,9 +34,14 @@ function createHarness(options?: {
|
||||
osd: [] as string[],
|
||||
feedback: [] as string[],
|
||||
resolveCalls: [] as string[],
|
||||
episodeLengths: [] as number[],
|
||||
connected: true,
|
||||
duration: options?.duration === undefined ? 1440 : options.duration,
|
||||
timePos: 0,
|
||||
chapterList: options?.chapterList ?? [],
|
||||
chapterListFails: false,
|
||||
// When set, chapter-list reads wait for it before answering.
|
||||
chapterGate: null as Promise<void> | null,
|
||||
};
|
||||
|
||||
const deps = {
|
||||
@@ -41,8 +49,9 @@ function createHarness(options?: {
|
||||
aniskipEnabled: state.enabled,
|
||||
aniskipButtonKey: state.buttonKey,
|
||||
}),
|
||||
resolveMetadataForFile: async (mediaPath) => {
|
||||
resolveMetadataForFile: async (mediaPath, episodeLength) => {
|
||||
state.resolveCalls.push(mediaPath);
|
||||
state.episodeLengths.push(episodeLength);
|
||||
const metadata = options?.metadata;
|
||||
if (typeof metadata === 'function') return metadata();
|
||||
return metadata ?? readyMetadata();
|
||||
@@ -51,7 +60,15 @@ function createHarness(options?: {
|
||||
state.commands.push(command);
|
||||
},
|
||||
requestMpvProperty: async (name) => {
|
||||
if (name === 'chapter-list') return state.chapterList;
|
||||
if (name === 'chapter-list') {
|
||||
if (state.chapterGate) await state.chapterGate;
|
||||
if (state.chapterListFails) throw new Error('property unavailable');
|
||||
return state.chapterList;
|
||||
}
|
||||
if (name === 'duration') {
|
||||
if (state.duration === null) throw new Error('property unavailable');
|
||||
return state.duration;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
isMpvConnected: () => state.connected,
|
||||
@@ -84,6 +101,10 @@ async function flushAsync(): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function seekCommands(commands: unknown[][]): unknown[][] {
|
||||
return commands.filter((command) => command[0] === 'set_property' && command[1] === 'time-pos');
|
||||
}
|
||||
|
||||
test('isRemoteMediaPath detects URLs but not local paths', () => {
|
||||
assert.equal(isRemoteMediaPath('https://example.com/stream.mkv'), true);
|
||||
assert.equal(isRemoteMediaPath('rtmp://example.com/live'), true);
|
||||
@@ -101,6 +122,7 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, ['/media/anime/My Show/ep1.mkv']);
|
||||
assert.deepEqual(state.episodeLengths, [1440]);
|
||||
const chapterCommands = chapterListCommands(state.commands);
|
||||
assert.equal(chapterCommands.length, 1);
|
||||
const chapters = chapterCommands[0]![2] as Array<{ time: number; title: string }>;
|
||||
@@ -109,7 +131,10 @@ test('media path change resolves metadata and sets AniSkip chapters', async () =
|
||||
{ time: 10, title: 'AniSkip Intro Start' },
|
||||
{ time: 95.5, title: 'AniSkip Intro End' },
|
||||
]);
|
||||
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 10, end: 95.5, source: 'aniskip' },
|
||||
outro: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('remote media paths and disabled config never resolve', async () => {
|
||||
@@ -131,21 +156,18 @@ test('skip intro seeks to intro end only inside the intro window', async () => {
|
||||
|
||||
state.timePos = 200;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Skip intro only during intro']);
|
||||
assert.deepEqual(state.osd, ['Skip only during intro or outro']);
|
||||
|
||||
state.timePos = 30;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Skip intro only during intro', 'Skipped intro']);
|
||||
const seek = state.commands.find(
|
||||
(command) => command[0] === 'set_property' && command[1] === 'time-pos',
|
||||
);
|
||||
assert.deepEqual(seek, ['set_property', 'time-pos', 95.5]);
|
||||
assert.deepEqual(state.osd, ['Skip only during intro or outro', 'Skipped intro']);
|
||||
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 95.5]]);
|
||||
});
|
||||
|
||||
test('skip intro reports unavailable when no window was found', () => {
|
||||
const { runtime, state } = createHarness();
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(state.osd, ['Intro skip unavailable']);
|
||||
assert.deepEqual(state.osd, ['Intro/outro skip unavailable']);
|
||||
});
|
||||
|
||||
test('time-pos prompt shows once near intro start', async () => {
|
||||
@@ -158,7 +180,7 @@ test('time-pos prompt shows once near intro start', async () => {
|
||||
|
||||
runtime.handleTimePosChange({ time: 10.5 });
|
||||
runtime.handleTimePosChange({ time: 11 });
|
||||
assert.deepEqual(state.osd, ['You can skip by pressing TAB']);
|
||||
assert.deepEqual(state.osd, ['You can skip the intro by pressing TAB']);
|
||||
});
|
||||
|
||||
test('prompt and skip messages use playback feedback when configured', async () => {
|
||||
@@ -170,7 +192,7 @@ test('prompt and skip messages use playback feedback when configured', async ()
|
||||
state.timePos = 30;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
|
||||
assert.deepEqual(state.feedback, ['You can skip by pressing TAB', 'Skipped intro']);
|
||||
assert.deepEqual(state.feedback, ['You can skip the intro by pressing TAB', 'Skipped intro']);
|
||||
assert.deepEqual(state.osd, []);
|
||||
});
|
||||
|
||||
@@ -240,18 +262,13 @@ test('aniskip refresh forces a fresh lookup for the current media', async () =>
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
});
|
||||
|
||||
test('media without an intro window is cached and never re-resolved on reload of another file', async () => {
|
||||
test('definite misses are cached and not looked up again for the same file', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({
|
||||
malId: 1234,
|
||||
introStart: null,
|
||||
introEnd: null,
|
||||
lookupStatus: 'missing_payload',
|
||||
}),
|
||||
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(runtime.getIntroWindow(), null);
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
assert.equal(chapterListCommands(state.commands).length, 0);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
|
||||
@@ -261,25 +278,117 @@ test('media without an intro window is cached and never re-resolved on reload of
|
||||
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/other.mkv']);
|
||||
});
|
||||
|
||||
test('transient lookup failures are retried on the next media load', async () => {
|
||||
let failures = 0;
|
||||
test('transient lookup failures are not cached and retry on the next media load', async () => {
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: async () => {
|
||||
failures += 1;
|
||||
return readyMetadata(
|
||||
failures === 1 ? { introStart: null, introEnd: null, lookupStatus: 'lookup_failed' } : {},
|
||||
);
|
||||
calls += 1;
|
||||
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(runtime.getIntroWindow(), null);
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '' });
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
assert.deepEqual(runtime.getIntroWindow(), { start: 10, end: 95.5, malId: 1234 });
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('resolution waits for a known duration before reading chapters or AniSkip', async () => {
|
||||
const { runtime, state } = createHarness({ duration: null });
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.resolveCalls, []);
|
||||
|
||||
runtime.handleDurationChange({ duration: 1425.2 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1425.2]);
|
||||
});
|
||||
|
||||
test('file chapters with both an opening and an ending skip the AniSkip lookup', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Prologue' },
|
||||
{ time: 120, title: 'Opening' },
|
||||
{ time: 210, title: 'Part A' },
|
||||
{ time: 1300, title: 'Ending' },
|
||||
{ time: 1390, title: 'Preview' },
|
||||
],
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, []);
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 120, end: 210, source: 'chapters' },
|
||||
outro: { start: 1300, end: 1390, source: 'chapters' },
|
||||
});
|
||||
// The file already has chapter boundaries there, so no AniSkip markers are added.
|
||||
assert.equal(chapterListCommands(state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('AniSkip fills in the window the file chapters lack', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
],
|
||||
metadata: readyMetadata({
|
||||
intro: { start: 3, end: 93 },
|
||||
outro: { start: 1330, end: 1420 },
|
||||
}),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.equal(state.resolveCalls.length, 1);
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: { start: 1330, end: 1420, source: 'aniskip' },
|
||||
});
|
||||
assert.deepEqual(chapterListCommands(state.commands)[0]![2], [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
{ time: 1330, title: 'AniSkip Outro Start' },
|
||||
{ time: 1420, title: 'AniSkip Outro End' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('remote streams use file chapters without an AniSkip lookup', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Intro' },
|
||||
{ time: 30, title: 'OP' },
|
||||
{ time: 120, title: 'Episode' },
|
||||
],
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: 'https://jellyfin.example/Videos/1/stream.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(state.resolveCalls, []);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 30, end: 120, source: 'chapters' });
|
||||
});
|
||||
|
||||
test('skip key skips the outro inside its window and prompts at its start', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({ outro: { start: 1330, end: 1420 } }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
runtime.handleTimePosChange({ time: 1331 });
|
||||
runtime.handleTimePosChange({ time: 1332 });
|
||||
assert.deepEqual(state.osd, ['You can skip the outro by pressing TAB']);
|
||||
|
||||
state.timePos = 1329.8;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
state.timePos = 1425;
|
||||
runtime.handleClientMessage({ args: ['subminer-skip-intro'] });
|
||||
assert.deepEqual(seekCommands(state.commands), [['set_property', 'time-pos', 1420]]);
|
||||
assert.deepEqual(state.osd.slice(1), ['Skipped outro', 'Skip only during intro or outro']);
|
||||
});
|
||||
|
||||
test('disconnect clears bindings so reconnect rebinds the skip key', () => {
|
||||
@@ -292,3 +401,174 @@ test('disconnect clears bindings so reconnect rebinds the skip key', () => {
|
||||
['keybind', 'TAB', 'script-message subminer-skip-intro'],
|
||||
]);
|
||||
});
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
test('a failed chapter-list read leaves the file chapters untouched', async () => {
|
||||
const harness = createHarness({
|
||||
chapterList: [{ time: 0, title: 'Prologue' }],
|
||||
metadata: async () => {
|
||||
harness.state.chapterListFails = true;
|
||||
return readyMetadata();
|
||||
},
|
||||
});
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.equal(harness.runtime.getSkipWindows().intro?.source, 'aniskip');
|
||||
assert.equal(chapterListCommands(harness.state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('markers are not written into a file that replaced the one being read', async () => {
|
||||
const gate = deferred<void>();
|
||||
let calls = 0;
|
||||
const harness = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
harness.state.chapterGate = gate.promise;
|
||||
return readyMetadata();
|
||||
}
|
||||
return readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' });
|
||||
},
|
||||
});
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/a.mkv' });
|
||||
await flushAsync();
|
||||
// The marker write for a.mkv is waiting on its chapter-list read.
|
||||
harness.runtime.handleMediaPathChange({ path: '/media/b.mkv' });
|
||||
harness.state.chapterGate = null;
|
||||
gate.resolve();
|
||||
await flushAsync();
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(harness.state.resolveCalls, ['/media/a.mkv', '/media/b.mkv']);
|
||||
assert.equal(chapterListCommands(harness.state.commands).length, 0);
|
||||
});
|
||||
|
||||
test('a file-chapter intro is usable while the AniSkip lookup is still running', async () => {
|
||||
const lookup = deferred<AniSkipMetadata>();
|
||||
const { runtime, state } = createHarness({
|
||||
chapterList: [
|
||||
{ time: 0, title: 'Opening' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
],
|
||||
metadata: () => lookup.promise,
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: null,
|
||||
});
|
||||
runtime.handleTimePosChange({ time: 1 });
|
||||
assert.equal(state.osd.length, 1);
|
||||
|
||||
lookup.resolve(
|
||||
readyMetadata({ intro: { start: 3, end: 93 }, outro: { start: 1330, end: 1420 } }),
|
||||
);
|
||||
await flushAsync();
|
||||
|
||||
assert.deepEqual(runtime.getSkipWindows(), {
|
||||
intro: { start: 0, end: 90, source: 'chapters' },
|
||||
outro: { start: 1330, end: 1420, source: 'aniskip' },
|
||||
});
|
||||
// The intro prompt already shown is not shown again.
|
||||
runtime.handleTimePosChange({ time: 1.5 });
|
||||
assert.equal(state.osd.length, 1);
|
||||
});
|
||||
|
||||
test('a lookup superseded by a refresh does not overwrite the cache', async () => {
|
||||
const first = deferred<AniSkipMetadata>();
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: () => {
|
||||
calls += 1;
|
||||
return calls === 1 ? first.promise : Promise.resolve(readyMetadata());
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleClientMessage({ args: ['subminer-aniskip-refresh'] });
|
||||
await flushAsync();
|
||||
first.resolve(readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }));
|
||||
await flushAsync();
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/other.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.resolveCalls, ['/media/show.mkv', '/media/show.mkv', '/media/other.mkv']);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('a same-media reload retries a transient lookup failure', async () => {
|
||||
let calls = 0;
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: async () => {
|
||||
calls += 1;
|
||||
return readyMetadata(calls === 1 ? { ...NO_SKIP_TIMES, lookupStatus: 'lookup_failed' } : {});
|
||||
},
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 2);
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 10, end: 95.5, source: 'aniskip' });
|
||||
});
|
||||
|
||||
test('a failed chapter-list read is retried on the next duration change or reload', async () => {
|
||||
const stream = 'https://jellyfin.example/Videos/1/stream.mkv';
|
||||
const chapters = [
|
||||
{ time: 0, title: 'OP' },
|
||||
{ time: 90, title: 'Episode' },
|
||||
];
|
||||
for (const retry of ['duration', 'reload'] as const) {
|
||||
const { runtime, state } = createHarness({ chapterList: chapters });
|
||||
state.chapterListFails = true;
|
||||
runtime.handleMediaPathChange({ path: stream });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows(), NO_SKIP_TIMES);
|
||||
|
||||
state.chapterListFails = false;
|
||||
if (retry === 'duration') runtime.handleDurationChange({ duration: 1440 });
|
||||
else runtime.handleMediaPathChange({ path: stream });
|
||||
await flushAsync();
|
||||
assert.deepEqual(runtime.getSkipWindows().intro, { start: 0, end: 90, source: 'chapters' });
|
||||
}
|
||||
});
|
||||
|
||||
test('a successful empty chapter list is not read again on a duration change', async () => {
|
||||
const { runtime, state } = createHarness({
|
||||
metadata: readyMetadata({ ...NO_SKIP_TIMES, lookupStatus: 'missing_payload' }),
|
||||
});
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleDurationChange({ duration: 1441 });
|
||||
await flushAsync();
|
||||
assert.equal(state.resolveCalls.length, 1);
|
||||
});
|
||||
|
||||
test('a cached lookup is reused only for the episode length it was fetched for', async () => {
|
||||
const { runtime, state } = createHarness();
|
||||
// A failing chapter read keeps resolution retrying on each duration change.
|
||||
state.chapterListFails = true;
|
||||
runtime.handleMediaPathChange({ path: '/media/show.mkv' });
|
||||
await flushAsync();
|
||||
runtime.handleDurationChange({ duration: 1440 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1440]);
|
||||
|
||||
runtime.handleDurationChange({ duration: 1500 });
|
||||
await flushAsync();
|
||||
assert.deepEqual(state.episodeLengths, [1440, 1500]);
|
||||
});
|
||||
+276
-122
@@ -1,11 +1,16 @@
|
||||
import type { AniSkipMetadata } from './aniskip-metadata';
|
||||
import {
|
||||
ANISKIP_CHAPTER_PREFIX,
|
||||
classifyChapterSkipIntervals,
|
||||
type SkipInterval,
|
||||
} from './aniskip-chapters';
|
||||
|
||||
/** mpv script-message that skips whichever of the intro or outro is playing. */
|
||||
export const ANISKIP_SKIP_INTRO_MESSAGE = 'subminer-skip-intro';
|
||||
export const ANISKIP_REFRESH_MESSAGE = 'subminer-aniskip-refresh';
|
||||
|
||||
const DEFAULT_ANISKIP_BUTTON_KEY = 'TAB';
|
||||
const LEGACY_ANISKIP_BUTTON_KEY = 'y-k';
|
||||
const ANISKIP_CHAPTER_PREFIX = 'AniSkip ';
|
||||
const SKIP_WINDOW_EPSILON_SECONDS = 0.35;
|
||||
const PROMPT_WINDOW_SECONDS = 3;
|
||||
const PROMPT_OSD_DURATION_MS = 3000;
|
||||
@@ -16,7 +21,7 @@ export interface AniSkipRuntimeConfig {
|
||||
|
||||
export interface AniSkipRuntimeDeps {
|
||||
getAniSkipConfig: () => AniSkipRuntimeConfig;
|
||||
resolveMetadataForFile: (mediaPath: string) => Promise<AniSkipMetadata>;
|
||||
resolveMetadataForFile: (mediaPath: string, episodeLength: number) => Promise<AniSkipMetadata>;
|
||||
sendMpvCommand: (command: unknown[]) => void;
|
||||
requestMpvProperty: (name: string) => Promise<unknown>;
|
||||
isMpvConnected: () => boolean;
|
||||
@@ -28,26 +33,65 @@ export interface AniSkipRuntimeDeps {
|
||||
logDebug: (message: string) => void;
|
||||
}
|
||||
|
||||
export interface AniSkipIntroWindow {
|
||||
start: number;
|
||||
end: number;
|
||||
export type SkipWindowKind = 'intro' | 'outro';
|
||||
|
||||
export interface AniSkipWindow extends SkipInterval {
|
||||
/** `chapters` = the file's own chapters; `aniskip` = the AniSkip database. */
|
||||
source: 'chapters' | 'aniskip';
|
||||
}
|
||||
|
||||
export interface AniSkipWindows {
|
||||
intro: AniSkipWindow | null;
|
||||
outro: AniSkipWindow | null;
|
||||
}
|
||||
|
||||
interface AniSkipLookupResult {
|
||||
intro: SkipInterval | null;
|
||||
outro: SkipInterval | null;
|
||||
malId: number | null;
|
||||
}
|
||||
|
||||
type MpvChapter = { time?: unknown; title?: unknown };
|
||||
|
||||
const KIND_LABEL: Record<SkipWindowKind, { chapter: string; word: string }> = {
|
||||
intro: { chapter: 'Intro', word: 'intro' },
|
||||
outro: { chapter: 'Outro', word: 'outro' },
|
||||
};
|
||||
|
||||
export function isRemoteMediaPath(mediaPath: string): boolean {
|
||||
return /^[a-zA-Z][\w+.-]*:\/\//.test(mediaPath.trim());
|
||||
}
|
||||
|
||||
function isAniSkipChapter(chapter: MpvChapter): boolean {
|
||||
return typeof chapter?.title === 'string' && chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX);
|
||||
}
|
||||
|
||||
function isUsableDuration(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the intro and outro for each loaded file (file chapters first, then
|
||||
* AniSkip for whatever the chapters lack), marks them as chapters, prompts when
|
||||
* one starts, and skips the active one when the skip key is pressed.
|
||||
*/
|
||||
export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
let requestGeneration = 0;
|
||||
let currentMediaPath = '';
|
||||
let introWindow: AniSkipIntroWindow | null = null;
|
||||
let promptShown = false;
|
||||
let currentDuration: number | null = null;
|
||||
// True once resolution for the current media has started (or finished).
|
||||
let resolutionStarted = false;
|
||||
// True when resolution for the current media hit a retryable failure (the
|
||||
// chapter-list read or the AniSkip lookup), so a reload or duration change
|
||||
// runs it again.
|
||||
let retryResolution = false;
|
||||
let windows: AniSkipWindows = { intro: null, outro: null };
|
||||
const promptShown: Record<SkipWindowKind, boolean> = { intro: false, outro: false };
|
||||
let boundButtonKey: string | null = null;
|
||||
let legacyFallbackBound = false;
|
||||
const introWindowCache = new Map<string, AniSkipIntroWindow | null>();
|
||||
// AniSkip results per media path, with the episode length they were fetched
|
||||
// for (v2 picks times by length). Only definitive answers are stored.
|
||||
const lookupCache = new Map<string, { duration: number; result: AniSkipLookupResult }>();
|
||||
|
||||
function resolveButtonKey(): string {
|
||||
const key = deps.getAniSkipConfig().aniskipButtonKey.trim();
|
||||
@@ -93,22 +137,39 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
}
|
||||
}
|
||||
|
||||
async function setIntroChapters(introStart: number, introEnd: number): Promise<void> {
|
||||
let existing: MpvChapter[] = [];
|
||||
async function readChapterList(): Promise<MpvChapter[] | null> {
|
||||
try {
|
||||
const chapterList = await deps.requestMpvProperty('chapter-list');
|
||||
if (Array.isArray(chapterList)) {
|
||||
existing = chapterList as MpvChapter[];
|
||||
}
|
||||
return Array.isArray(chapterList) ? (chapterList as MpvChapter[]) : [];
|
||||
} catch {
|
||||
// chapter-list may be unavailable mid-load; fall back to AniSkip chapters only
|
||||
// chapter-list may be unavailable mid-load
|
||||
return null;
|
||||
}
|
||||
const chapters = existing.filter(
|
||||
(chapter) =>
|
||||
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
|
||||
);
|
||||
chapters.push({ time: introStart, title: 'AniSkip Intro Start' });
|
||||
chapters.push({ time: introEnd, title: 'AniSkip Intro End' });
|
||||
}
|
||||
|
||||
/** True while the given request generation still owns the given media. */
|
||||
function ownsPlayback(generation: number, mediaPath: string): boolean {
|
||||
return generation === requestGeneration && mediaPath === currentMediaPath;
|
||||
}
|
||||
|
||||
/** Replaces SubMiner's marker chapters with ones for the AniSkip-sourced windows. */
|
||||
async function setSkipChapters(): Promise<void> {
|
||||
const generation = requestGeneration;
|
||||
const mediaPath = currentMediaPath;
|
||||
const markers: MpvChapter[] = [];
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (window?.source !== 'aniskip') continue;
|
||||
const label = KIND_LABEL[kind].chapter;
|
||||
markers.push({ time: window.start, title: `${ANISKIP_CHAPTER_PREFIX}${label} Start` });
|
||||
markers.push({ time: window.end, title: `${ANISKIP_CHAPTER_PREFIX}${label} End` });
|
||||
}
|
||||
if (markers.length === 0) return;
|
||||
const existing = await readChapterList();
|
||||
// A failed read must not wipe the file's chapters, and a read that finished
|
||||
// after the media changed must not write into the next file.
|
||||
if (!existing || !ownsPlayback(generation, mediaPath)) return;
|
||||
const chapters = existing.filter((chapter) => !isAniSkipChapter(chapter)).concat(markers);
|
||||
chapters.sort((a, b) => {
|
||||
const aTime = typeof a.time === 'number' ? a.time : 0;
|
||||
const bTime = typeof b.time === 'number' ? b.time : 0;
|
||||
@@ -117,21 +178,13 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
deps.sendMpvCommand(['set_property', 'chapter-list', chapters]);
|
||||
}
|
||||
|
||||
async function removeIntroChapters(): Promise<void> {
|
||||
async function removeSkipChapters(): Promise<void> {
|
||||
if (!deps.isMpvConnected()) return;
|
||||
let existing: MpvChapter[] = [];
|
||||
try {
|
||||
const chapterList = await deps.requestMpvProperty('chapter-list');
|
||||
if (Array.isArray(chapterList)) {
|
||||
existing = chapterList as MpvChapter[];
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const filtered = existing.filter(
|
||||
(chapter) =>
|
||||
typeof chapter?.title !== 'string' || !chapter.title.startsWith(ANISKIP_CHAPTER_PREFIX),
|
||||
);
|
||||
const generation = requestGeneration;
|
||||
const mediaPath = currentMediaPath;
|
||||
const existing = await readChapterList();
|
||||
if (!existing || !ownsPlayback(generation, mediaPath)) return;
|
||||
const filtered = existing.filter((chapter) => !isAniSkipChapter(chapter));
|
||||
if (filtered.length !== existing.length) {
|
||||
deps.sendMpvCommand(['set_property', 'chapter-list', filtered]);
|
||||
}
|
||||
@@ -139,81 +192,162 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
|
||||
function clearState(): void {
|
||||
requestGeneration += 1;
|
||||
introWindow = null;
|
||||
promptShown = false;
|
||||
resolutionStarted = false;
|
||||
retryResolution = false;
|
||||
windows = { intro: null, outro: null };
|
||||
promptShown.intro = false;
|
||||
promptShown.outro = false;
|
||||
}
|
||||
|
||||
async function applyIntroWindow(window: AniSkipIntroWindow): Promise<void> {
|
||||
introWindow = window;
|
||||
promptShown = false;
|
||||
await setIntroChapters(window.start, window.end);
|
||||
function logWindow(kind: SkipWindowKind, window: AniSkipWindow, malId: number | null): void {
|
||||
deps.logInfo(
|
||||
`AniSkip intro window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (MAL ${
|
||||
window.malId ?? '-'
|
||||
})`,
|
||||
`AniSkip ${kind} window ${window.start.toFixed(3)} -> ${window.end.toFixed(3)} (source=${
|
||||
window.source
|
||||
}, MAL ${malId ?? '-'})`,
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveForMedia(mediaPath: string, options?: { force?: boolean }): Promise<void> {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
if (!mediaPath || isRemoteMediaPath(mediaPath)) {
|
||||
deps.logDebug('AniSkip lookup skipped: no local media path');
|
||||
return;
|
||||
/** Installs the file-chapter windows, resetting the prompts. */
|
||||
function applyChapterWindows(next: AniSkipWindows): void {
|
||||
windows = next;
|
||||
promptShown.intro = false;
|
||||
promptShown.outro = false;
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = next[kind];
|
||||
if (window) logWindow(kind, window, null);
|
||||
}
|
||||
}
|
||||
|
||||
if (options?.force) {
|
||||
introWindowCache.delete(mediaPath);
|
||||
/**
|
||||
* Fills the windows the chapters lacked from AniSkip, leaving the chapter
|
||||
* windows (and whether their prompt was shown) untouched.
|
||||
*/
|
||||
async function mergeAniSkipWindows(lookup: AniSkipLookupResult): Promise<void> {
|
||||
const added: SkipWindowKind[] = [];
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const interval = lookup[kind];
|
||||
if (windows[kind] || !interval) continue;
|
||||
windows = { ...windows, [kind]: { ...interval, source: 'aniskip' } };
|
||||
promptShown[kind] = false;
|
||||
added.push(kind);
|
||||
}
|
||||
const generation = requestGeneration;
|
||||
const cached = introWindowCache.get(mediaPath);
|
||||
if (cached !== undefined) {
|
||||
if (cached) {
|
||||
await applyIntroWindow(cached);
|
||||
}
|
||||
return;
|
||||
if (added.length === 0) return;
|
||||
for (const kind of added) {
|
||||
const window = windows[kind];
|
||||
if (window) logWindow(kind, window, lookup.malId);
|
||||
}
|
||||
await setSkipChapters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up AniSkip, using the cache for definitive answers fetched at the same
|
||||
* episode length. Null means a retryable failure.
|
||||
*/
|
||||
async function lookUpAniSkip(
|
||||
mediaPath: string,
|
||||
duration: number,
|
||||
generation: number,
|
||||
): Promise<AniSkipLookupResult | null> {
|
||||
const cached = lookupCache.get(mediaPath);
|
||||
if (cached?.duration === duration) return cached.result;
|
||||
|
||||
let metadata: AniSkipMetadata;
|
||||
try {
|
||||
metadata = await deps.resolveMetadataForFile(mediaPath);
|
||||
metadata = await deps.resolveMetadataForFile(mediaPath, duration);
|
||||
} catch (error) {
|
||||
deps.logWarn('AniSkip metadata lookup failed', error);
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
if (generation !== requestGeneration || mediaPath !== currentMediaPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
metadata.lookupStatus !== 'ready' ||
|
||||
metadata.introStart === null ||
|
||||
metadata.introEnd === null ||
|
||||
metadata.introEnd <= metadata.introStart
|
||||
) {
|
||||
// Only definitive "no skip window exists" results are cached; transient
|
||||
// lookup failures stay retryable on the next load or refresh.
|
||||
if (metadata.lookupStatus !== 'lookup_failed') {
|
||||
introWindowCache.set(mediaPath, null);
|
||||
}
|
||||
deps.logInfo(
|
||||
`AniSkip: no intro window for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const window: AniSkipIntroWindow = {
|
||||
start: metadata.introStart,
|
||||
end: metadata.introEnd,
|
||||
const result: AniSkipLookupResult = {
|
||||
intro: metadata.intro,
|
||||
outro: metadata.outro,
|
||||
malId: metadata.malId,
|
||||
};
|
||||
introWindowCache.set(mediaPath, window);
|
||||
await applyIntroWindow(window);
|
||||
if (metadata.lookupStatus === 'lookup_failed') {
|
||||
deps.logInfo(`AniSkip lookup failed for "${metadata.title}"; will retry on next load`);
|
||||
return null;
|
||||
}
|
||||
// Every other status is definitive (a 404 or an unmatched title), so cache it,
|
||||
// unless a refresh or media change superseded this lookup while it ran.
|
||||
if (generation === requestGeneration) lookupCache.set(mediaPath, { duration, result });
|
||||
if (metadata.lookupStatus !== 'ready') {
|
||||
deps.logInfo(
|
||||
`AniSkip: no skip times for "${metadata.title}" (status=${metadata.lookupStatus ?? 'unknown'})`,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function skipIntroNow(): void {
|
||||
async function resolveForMedia(mediaPath: string, duration: number): Promise<void> {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
if (!introWindow) {
|
||||
showPlaybackFeedback('Intro skip unavailable');
|
||||
const generation = requestGeneration;
|
||||
const isStale = () => generation !== requestGeneration || mediaPath !== currentMediaPath;
|
||||
|
||||
const chapterList = await readChapterList();
|
||||
if (isStale()) return;
|
||||
// A failed read is retried later; a successful empty list is a final answer.
|
||||
if (chapterList === null) retryResolution = true;
|
||||
const fromChapters = classifyChapterSkipIntervals(chapterList ?? [], duration);
|
||||
const next: AniSkipWindows = {
|
||||
intro: fromChapters.intro ? { ...fromChapters.intro, source: 'chapters' } : null,
|
||||
outro: fromChapters.outro ? { ...fromChapters.outro, source: 'chapters' } : null,
|
||||
};
|
||||
// Chapter windows work right away; AniSkip only fills what they lack.
|
||||
applyChapterWindows(next);
|
||||
if (next.intro && next.outro) return;
|
||||
if (isRemoteMediaPath(mediaPath)) {
|
||||
deps.logDebug('AniSkip lookup skipped for remote media; using file chapters only');
|
||||
return;
|
||||
}
|
||||
|
||||
const lookup = await lookUpAniSkip(mediaPath, duration, generation);
|
||||
if (isStale()) return;
|
||||
if (lookup === null) retryResolution = true;
|
||||
if (lookup) await mergeAniSkipWindows(lookup);
|
||||
}
|
||||
|
||||
/** Starts resolution once the current media has both a path and a known duration. */
|
||||
function maybeStartResolution(): void {
|
||||
if (resolutionStarted || !currentMediaPath || currentDuration === null) return;
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
resolutionStarted = true;
|
||||
void resolveForMedia(currentMediaPath, currentDuration).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
}
|
||||
|
||||
function requestCurrentDuration(): void {
|
||||
const generation = requestGeneration;
|
||||
void deps
|
||||
.requestMpvProperty('duration')
|
||||
.then((value) => {
|
||||
if (generation !== requestGeneration || !isUsableDuration(value)) return;
|
||||
currentDuration ??= value;
|
||||
maybeStartResolution();
|
||||
})
|
||||
.catch(() => {
|
||||
// duration is unavailable until the file is loaded; duration-change will follow
|
||||
});
|
||||
}
|
||||
|
||||
function getActiveWindow(now: number): SkipWindowKind | null {
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (
|
||||
window &&
|
||||
now >= window.start - SKIP_WINDOW_EPSILON_SECONDS &&
|
||||
now <= window.end + SKIP_WINDOW_EPSILON_SECONDS
|
||||
) {
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function skipNow(): void {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
if (!windows.intro && !windows.outro) {
|
||||
showPlaybackFeedback('Intro/outro skip unavailable');
|
||||
return;
|
||||
}
|
||||
const now = deps.getCurrentTimePos();
|
||||
@@ -221,40 +355,56 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
showPlaybackFeedback('Skip unavailable');
|
||||
return;
|
||||
}
|
||||
if (
|
||||
now < introWindow.start - SKIP_WINDOW_EPSILON_SECONDS ||
|
||||
now > introWindow.end + SKIP_WINDOW_EPSILON_SECONDS
|
||||
) {
|
||||
showPlaybackFeedback('Skip intro only during intro');
|
||||
const kind = getActiveWindow(now);
|
||||
const window = kind ? windows[kind] : null;
|
||||
if (!kind || !window) {
|
||||
showPlaybackFeedback('Skip only during intro or outro');
|
||||
return;
|
||||
}
|
||||
deps.sendMpvCommand(['set_property', 'time-pos', introWindow.end]);
|
||||
showPlaybackFeedback('Skipped intro');
|
||||
deps.sendMpvCommand(['set_property', 'time-pos', window.end]);
|
||||
showPlaybackFeedback(`Skipped ${KIND_LABEL[kind].word}`);
|
||||
}
|
||||
|
||||
function handleTimePosChange({ time }: { time: number }): void {
|
||||
if (!introWindow || promptShown) return;
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
const promptWindowEnd = Math.min(introWindow.start + PROMPT_WINDOW_SECONDS, introWindow.end);
|
||||
if (time >= introWindow.start && time < promptWindowEnd) {
|
||||
promptShown = true;
|
||||
showPlaybackFeedback(`You can skip by pressing ${resolveButtonKey()}`);
|
||||
for (const kind of ['intro', 'outro'] as const) {
|
||||
const window = windows[kind];
|
||||
if (!window || promptShown[kind]) continue;
|
||||
const promptWindowEnd = Math.min(window.start + PROMPT_WINDOW_SECONDS, window.end);
|
||||
if (time >= window.start && time < promptWindowEnd) {
|
||||
promptShown[kind] = true;
|
||||
showPlaybackFeedback(
|
||||
`You can skip the ${KIND_LABEL[kind].word} by pressing ${resolveButtonKey()}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handleDurationChange({ duration }: { duration: number }): void {
|
||||
if (!isUsableDuration(duration) || !currentMediaPath) return;
|
||||
currentDuration = duration;
|
||||
if (retryResolution) clearState();
|
||||
maybeStartResolution();
|
||||
}
|
||||
|
||||
function handleMediaPathChange({ path }: { path: string }): void {
|
||||
const nextPath = typeof path === 'string' ? path : '';
|
||||
if (nextPath === currentMediaPath && introWindow) {
|
||||
if (nextPath === currentMediaPath && resolutionStarted) {
|
||||
if (retryResolution) {
|
||||
// The last resolution failed transiently; a reload is the retry.
|
||||
clearState();
|
||||
maybeStartResolution();
|
||||
return;
|
||||
}
|
||||
// Same-media reload: mpv rebuilt the chapter list, so re-apply markers.
|
||||
void setIntroChapters(introWindow.start, introWindow.end).catch(() => {});
|
||||
void setSkipChapters().catch(() => {});
|
||||
return;
|
||||
}
|
||||
currentMediaPath = nextPath;
|
||||
currentDuration = null;
|
||||
clearState();
|
||||
if (!nextPath) return;
|
||||
void resolveForMedia(nextPath).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
if (!nextPath || !deps.getAniSkipConfig().aniskipEnabled) return;
|
||||
requestCurrentDuration();
|
||||
}
|
||||
|
||||
function handleConnectionChange({ connected }: { connected: boolean }): void {
|
||||
@@ -263,6 +413,7 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
legacyFallbackBound = false;
|
||||
clearState();
|
||||
currentMediaPath = '';
|
||||
currentDuration = null;
|
||||
return;
|
||||
}
|
||||
bindSkipKeys();
|
||||
@@ -271,43 +422,46 @@ export function createAniSkipRuntime(deps: AniSkipRuntimeDeps) {
|
||||
function handleClientMessage({ args }: { args: string[] }): void {
|
||||
const messageName = args[0];
|
||||
if (messageName === ANISKIP_SKIP_INTRO_MESSAGE) {
|
||||
skipIntroNow();
|
||||
skipNow();
|
||||
return;
|
||||
}
|
||||
if (messageName === ANISKIP_REFRESH_MESSAGE) {
|
||||
const mediaPath = currentMediaPath;
|
||||
if (!mediaPath) return;
|
||||
if (!currentMediaPath) return;
|
||||
lookupCache.delete(currentMediaPath);
|
||||
clearState();
|
||||
void removeIntroChapters().catch(() => {});
|
||||
void resolveForMedia(mediaPath, { force: true }).catch((error) => {
|
||||
deps.logWarn('AniSkip refresh failed', error);
|
||||
});
|
||||
void removeSkipChapters().catch(() => {});
|
||||
if (currentDuration === null) {
|
||||
requestCurrentDuration();
|
||||
return;
|
||||
}
|
||||
maybeStartResolution();
|
||||
}
|
||||
}
|
||||
|
||||
function applyConfigChange(): void {
|
||||
bindSkipKeys();
|
||||
const enabled = deps.getAniSkipConfig().aniskipEnabled;
|
||||
if (!enabled) {
|
||||
if (!deps.getAniSkipConfig().aniskipEnabled) {
|
||||
clearState();
|
||||
void removeIntroChapters().catch(() => {});
|
||||
void removeSkipChapters().catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (!introWindow && currentMediaPath) {
|
||||
void resolveForMedia(currentMediaPath).catch((error) => {
|
||||
deps.logWarn('AniSkip media resolution failed', error);
|
||||
});
|
||||
if (!currentMediaPath || resolutionStarted) return;
|
||||
if (currentDuration === null) {
|
||||
requestCurrentDuration();
|
||||
return;
|
||||
}
|
||||
maybeStartResolution();
|
||||
}
|
||||
|
||||
return {
|
||||
handleConnectionChange,
|
||||
handleMediaPathChange,
|
||||
handleDurationChange,
|
||||
handleTimePosChange,
|
||||
handleClientMessage,
|
||||
applyConfigChange,
|
||||
skipIntroNow,
|
||||
getIntroWindow: () => introWindow,
|
||||
skipNow,
|
||||
getSkipWindows: (): AniSkipWindows => windows,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user