feat(jellyfin): queue series neighbor episodes in the mpv playlist (#338)

This commit is contained in:
sudacode authored and GitHub committed 2026-11-24 01:45:27 -08:00
1 parent 713cdb3ef8
commit 926e6b047e
45 files changed
+2295 -197

No files matched your search

+35
View File
@@ -8,6 +8,7 @@ import {
JellyfinPlaybackReporter,
JellyfinRemoteSessionService,
jellyfinTicksToSecondsRuntime,
listJellyfinSeriesEpisodeIdsRuntime,
listJellyfinItemsRuntime,
listJellyfinLibrariesRuntime,
listJellyfinSubtitleTracksRuntime,
@@ -28,6 +29,7 @@ import {
mergeJellyfinRecentServers,
parseJellyfinSetupSubmissionUrl,
persistJellyfinAuthSession,
markJellyfinRemotePlaybackLoaded,
type ActiveJellyfinRemotePlaybackState,
} from '../runtime/domains/jellyfin';
import { detectInstalledMpvPlugin } from '../runtime/first-run-setup-plugin';
@@ -37,6 +39,10 @@ import {
createHostDerivedJellyfinDeviceId,
resolveJellyfinRemoteDeviceName,
} from '../runtime/jellyfin-device-identity';
import {
chooseMpvEntryLoadMode,
PLUGIN_ENTRY_OPTIONS_USER_DATA,
} from '../runtime/jellyfin-episode-playlist';
import { createJellyfinSubtitleCacheIo } from '../runtime/jellyfin-subtitle-cache-io';
import { clearJellyfinAuthSessionAndRefreshTray as clearJellyfinAuthSessionAndRefreshTrayRuntime } from '../runtime/jellyfin-tray-discovery';
import { resolveMpvExecutablePath, spawnMpvProcess } from '../runtime/mpv-process';
@@ -140,6 +146,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
runJellyfinCommand,
openJellyfinSetupWindow,
ensureMpvConnectedForPlayback,
playJellyfinItemInMpv,
} = composeJellyfinRuntimeHandlers({
getResolvedJellyfinConfigMainDeps: {
getResolvedConfig: () => configService.getConfig(),
@@ -237,6 +244,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
setTimeout(callback, delayMs);
},
convertTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks),
getActivePlayback: () => activeJellyfinRemotePlayback,
setActivePlayback: (state) => {
activeJellyfinRemotePlayback = {
...(state as ActiveJellyfinRemotePlaybackState),
@@ -270,6 +278,24 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
deps.ensureImmersionTrackerStarted();
appState.immersionTracker?.recordJellyfinPlaybackMetadata(metadata);
},
getEpisodePlaylistSettings: () => configService.getConfig().jellyfin.episodePlaylist,
listSeriesEpisodeIds: ({ session, clientInfo, seriesId }) =>
listJellyfinSeriesEpisodeIdsRuntime(session, clientInfo, seriesId),
readMpvPlaylist: async () => appState.mpvClient?.requestProperty('playlist') ?? [],
resolveEntryLoadMode: async () => {
const client = appState.mpvClient;
if (!client) return 'loadfile';
// The user-data key is unset (an error) unless the SubMiner plugin is loaded.
const [mpvVersion, pluginAppliesEntryOptions] = await Promise.all([
client.requestProperty('mpv-version').catch(() => null),
client.requestProperty(PLUGIN_ENTRY_OPTIONS_USER_DATA).then(
(value) => value === true,
() => false,
),
]);
return chooseMpvEntryLoadMode(mpvVersion, pluginAppliesEntryOptions);
},
logDebug: (message, error) => logger.debug(message, error),
},
remoteComposerOptions: {
getConfiguredSession: () => getConfiguredJellyfinSession(getResolvedJellyfinConfig()),
@@ -452,6 +478,15 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
ensureMpvConnectedForPlayback,
getTrayDiscoveryDeps: getJellyfinTrayDiscoveryDeps,
getActivePlayback: () => activeJellyfinRemotePlayback,
/**
* Called with each new mpv path: takes over a queued Jellyfin episode mpv started from its
* playlist, otherwise marks the active playback loaded. Must run before the immersion sync.
*/
handleMediaPathLoaded: (path: string) => {
if (playJellyfinItemInMpv.adoptQueuedEpisode(path)) return;
markJellyfinRemotePlaybackLoaded(activeJellyfinRemotePlayback, path);
},
handlePlaybackTimePos: () => playJellyfinItemInMpv.handlePlaybackTimePos(),
getQuitOnDisconnectArmed: () => jellyfinPlayQuitOnDisconnectArmed,
};
}
+2
View File
@@ -111,6 +111,8 @@ function makeDeps(recorder: Recorder): PlaybackAssemblyDeps {
reportJellyfinRemoteStopped: spy('jellyfin.reportStopped', resolved),
reportJellyfinRemoteProgress: spy('jellyfin.reportProgress', resolved),
getActivePlayback: spy('jellyfin.getActivePlayback', () => null),
handleMediaPathLoaded: spy('jellyfin.handleMediaPathLoaded', noop),
handlePlaybackTimePos: spy('jellyfin.handlePlaybackTimePos', noop),
startJellyfinRemoteSession: spy('jellyfin.startRemoteSession', resolved),
},
anilist: {
+6 -6
View File
@@ -21,10 +21,7 @@ import { createAutoplayTokenizationWarmRelease } from '../runtime/autoplay-token
import { composeMpvRuntimeHandlers } from '../runtime/composers';
import { createCurrentMediaTokenizationGate } from '../runtime/current-media-tokenization-gate';
import { createCachedInternalSubtitleTrackExtractor } from '../runtime/internal-subtitle-extraction';
import {
markJellyfinRemotePlaybackLoaded as markJellyfinRemotePlaybackLoadedState,
shouldAutoLoadSecondarySubTrackForJellyfinPlayback,
} from '../runtime/jellyfin-remote-playback';
import { shouldAutoLoadSecondarySubTrackForJellyfinPlayback } from '../runtime/jellyfin-remote-playback';
import { createJimakuAutoOpenRuntime } from '../runtime/jimaku-auto-open';
import { createManagedLocalSubtitleSelectionRuntime } from '../runtime/local-subtitle-selection';
import { focusMacOSOverlayWindow } from '../runtime/macos-overlay-window-focus';
@@ -164,6 +161,8 @@ export interface PlaybackAssemblyDeps {
| 'reportJellyfinRemoteStopped'
| 'reportJellyfinRemoteProgress'
| 'getActivePlayback'
| 'handleMediaPathLoaded'
| 'handlePlaybackTimePos'
| 'startJellyfinRemoteSession'
>;
anilist: Pick<
@@ -838,8 +837,8 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
immersionMediaRuntime.syncFromCurrentMediaState();
},
signalAutoplayReadyIfWarm: (path) => signalAutoplayReadyFromWarmTokenization?.(path),
markJellyfinRemotePlaybackLoaded: (path) => {
markJellyfinRemotePlaybackLoadedState(jellyfin.getActivePlayback(), path);
handleJellyfinMediaPathLoaded: (path) => {
jellyfin.handleMediaPathLoaded(path);
},
scheduleCharacterDictionarySync: () => {
if (
@@ -862,6 +861,7 @@ export function createPlaybackAssembly(deps: PlaybackAssemblyDeps) {
},
consumeExplicitSeek: () => consumeExplicitSeekIntent(),
onTimePosUpdate: (time) => {
jellyfin.handlePlaybackTimePos();
const delta = time - lastObservedTimePos;
if (subtitlePrefetchService && (delta > SEEK_THRESHOLD_SECONDS || delta < 0)) {
subtitlePrefetchService.onSeek(time);
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import type { ActiveJellyfinRemotePlaybackState } from '../jellyfin-remote-commands';
import { composeJellyfinRemoteHandlers } from './jellyfin-remote-composer';
function makeHandlers() {
return composeJellyfinRemoteHandlers({
getConfiguredSession: () => null,
getClientInfo: () => ({ clientName: 'SubMiner', clientVersion: '1', deviceId: 'did' }),
getJellyfinConfig: () => ({}),
playJellyfinItem: async () => {},
logWarn: () => {},
getMpvClient: () => null,
sendMpvCommand: () => {},
jellyfinTicksToSeconds: (ticks) => ticks / 10_000_000,
getActivePlayback: () => null,
clearActivePlayback: () => {},
getNow: () => 0,
getLastProgressAtMs: () => 0,
setLastProgressAtMs: () => {},
progressIntervalMs: 3000,
ticksPerSecond: 10_000_000,
logDebug: () => {},
});
}
test('a tracked episode start holds its own stop and the next transition', async () => {
const handlers = makeHandlers();
const events: string[] = [];
const playback: ActiveJellyfinRemotePlaybackState = {
itemId: 'ep1',
playMethod: 'DirectPlay',
reporter: {
reportPlaying: async () => {},
reportProgress: async () => {},
reportStopped: async () => void events.push('stopped:ep1'),
},
};
let finishStart = () => {};
handlers.trackJellyfinPlaybackStart(
new Promise<void>((resolve) => {
finishStart = () => {
events.push('started:ep1');
resolve();
};
}),
playback,
);
const stopped = handlers.reportJellyfinPlaybackSuperseded(playback);
const transitionsDone = handlers.waitForJellyfinTransitionReports().then(() => {
events.push('transitions settled');
});
await Promise.resolve();
assert.deepEqual(events, [], 'the stop and the next start wait for the start in flight');
finishStart();
await Promise.all([stopped, transitionsDone]);
assert.deepEqual(events, ['started:ep1', 'stopped:ep1', 'transitions settled']);
});
@@ -5,6 +5,7 @@ import {
createJellyfinRemoteReportTracker,
createReportJellyfinRemoteProgressHandler,
createReportJellyfinRemoteStoppedHandler,
createReportSupersededJellyfinPlaybackHandler,
type JellyfinRemoteGeneralCommandHandlerDeps,
type JellyfinRemotePlayHandlerDeps,
type JellyfinRemotePlaystateHandlerDeps,
@@ -40,6 +41,16 @@ export type JellyfinRemoteComposerOptions = ComposerInputs<{
export type JellyfinRemoteComposerResult = ComposerOutputs<{
reportJellyfinRemoteProgress: ReturnType<typeof createReportJellyfinRemoteProgressHandler>;
reportJellyfinRemoteStopped: ReturnType<typeof createReportJellyfinRemoteStoppedHandler>;
reportJellyfinPlaybackSuperseded: ReturnType<
typeof createReportSupersededJellyfinPlaybackHandler
>;
/** Resolves once no episode start or stop report is in flight. */
waitForJellyfinTransitionReports: () => Promise<void>;
/** Tracks an episode start report, so its own stop and later starts wait for it. */
trackJellyfinPlaybackStart: (
report: Promise<void>,
playback: Parameters<ReturnType<typeof createReportSupersededJellyfinPlaybackHandler>>[0],
) => void;
handleJellyfinRemotePlay: (payload: RemotePlayPayload) => Promise<void>;
handleJellyfinRemotePlaystate: (payload: RemotePlaystatePayload) => Promise<void>;
handleJellyfinRemoteGeneralCommand: (payload: RemoteGeneralPayload) => Promise<void>;
@@ -61,7 +72,10 @@ export function composeJellyfinRemoteHandlers(
logDebug: options.logDebug,
reportTracker,
});
const reportJellyfinRemoteStopped = createReportJellyfinRemoteStoppedHandler({
// Every episode start and stop report in flight. Jellyfin keeps whichever start arrives last
// as the now-playing item and clears it on any stop, so a start waits for all of these.
const transitionReportTracker = createJellyfinRemoteReportTracker();
const reportStopped = createReportJellyfinRemoteStoppedHandler({
getActivePlayback: options.getActivePlayback,
clearActivePlayback: options.clearActivePlayback,
getMpvClient: options.getMpvClient,
@@ -71,10 +85,35 @@ export function composeJellyfinRemoteHandlers(
logWarn: options.logWarn,
reportTracker,
});
const reportSuperseded = createReportSupersededJellyfinPlaybackHandler({
ticksPerSecond: options.ticksPerSecond,
logDebug: options.logDebug,
logWarn: options.logWarn,
reportTracker,
});
const reportJellyfinRemoteStopped = (): Promise<void> => {
const report = reportStopped();
transitionReportTracker.track(report, null);
return report;
};
const reportJellyfinPlaybackSuperseded = (
playback: Parameters<typeof reportSuperseded>[0],
): Promise<void> => {
const report = reportSuperseded(playback);
transitionReportTracker.track(report, playback);
return report;
};
return {
reportJellyfinRemoteProgress,
reportJellyfinRemoteStopped,
reportJellyfinPlaybackSuperseded,
waitForJellyfinTransitionReports: () => transitionReportTracker.settled(),
trackJellyfinPlaybackStart: (report, playback) => {
// Tagged with its playback in the shared tracker, so that playback's stop waits for it.
reportTracker.track(report, playback);
transitionReportTracker.track(report, playback);
},
handleJellyfinRemotePlay: createHandleJellyfinRemotePlay({
getConfiguredSession: options.getConfiguredSession,
getClientInfo: options.getClientInfo,
@@ -50,7 +50,11 @@ export type JellyfinRuntimeComposerOptions = ComposerInputs<{
>[0];
playJellyfinItemInMpvMainDeps: Omit<
PlayJellyfinItemMainDeps,
'ensureMpvConnectedForPlayback' | 'preloadExternalSubtitles'
| 'ensureMpvConnectedForPlayback'
| 'preloadExternalSubtitles'
| 'reportPlaybackSuperseded'
| 'waitForTransitionReports'
| 'trackPlaybackStart'
>;
remoteComposerOptions: Omit<
JellyfinRemoteComposerOptions,
@@ -157,11 +161,18 @@ export function composeJellyfinRuntimeHandlers(
preloadExternalSubtitles: (params) => {
void preloadJellyfinExternalSubtitles(params);
},
// The remote handlers are built below and share the report tracker with the stop handler.
reportPlaybackSuperseded: (playback) => reportJellyfinPlaybackSuperseded(playback),
waitForTransitionReports: () => waitForJellyfinTransitionReports(),
trackPlaybackStart: (report, playback) => trackJellyfinPlaybackStart(report, playback),
});
const {
reportJellyfinRemoteProgress,
reportJellyfinRemoteStopped,
reportJellyfinPlaybackSuperseded,
waitForJellyfinTransitionReports,
trackJellyfinPlaybackStart,
handleJellyfinRemotePlay,
handleJellyfinRemotePlaystate,
handleJellyfinRemoteGeneralCommand,
@@ -0,0 +1,289 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
buildMpvEntryLoadCommands,
chooseMpvEntryLoadMode,
createJellyfinEpisodePlaylist,
selectEpisodeWindow,
type JellyfinEpisodePlaylistSettings,
type JellyfinPlaylistEntry,
type MpvEntryLoadMode,
} from './jellyfin-episode-playlist';
const EPISODES = ['e1', 'e2', 'e3', 'e4', 'e5', 'e6'];
test('selectEpisodeWindow centers on the current episode and stays full at series edges', () => {
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e3', 3), {
previousIds: ['e2'],
nextIds: ['e4'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e3', 4), {
previousIds: ['e2'],
nextIds: ['e4', 'e5'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e1', 3), {
previousIds: [],
nextIds: ['e2', 'e3'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'e6', 3), {
previousIds: ['e4', 'e5'],
nextIds: [],
});
assert.deepEqual(selectEpisodeWindow(['e1', 'e2'], 'e1', 5), {
previousIds: [],
nextIds: ['e2'],
});
assert.deepEqual(selectEpisodeWindow(EPISODES, 'missing', 3), { previousIds: [], nextIds: [] });
});
type Entry = JellyfinPlaylistEntry;
const url = (itemId: string) => `https://jf.example/Videos/${itemId}/stream`;
const entry = (itemId: string): Entry => ({
itemId,
seriesId: 'series',
playbackUrl: url(itemId),
fileOptions: [['start', itemId]],
title: `Show ${itemId}`,
});
/** mpv's playlist, kept in sync with the commands the queue sends. */
function makeHarness(
settings: JellyfinEpisodePlaylistSettings = { enabled: true, maxEpisodes: 3 },
mode: MpvEntryLoadMode = 'loadfile',
) {
const playlist: Array<{ filename: string; current: boolean; title?: string }> = [];
const commands: Array<Array<string | number>> = [];
let episodeListCalls = 0;
let afterRead: (() => void) | undefined;
const queue = createJellyfinEpisodePlaylist<null, Entry>({
getSettings: () => settings,
listSeriesEpisodeIds: async () => {
episodeListCalls += 1;
return EPISODES;
},
prepareEntry: async (_context, itemId) => entry(itemId),
getEntryLoadMode: () => mode,
readMpvPlaylist: async () => {
const snapshot = playlist.map((item) => ({ ...item }));
// Lets a test move mpv on after the read, like a keypress landing mid-run.
afterRead?.();
return snapshot;
},
sendMpvCommand: (command) => {
commands.push(command);
if (command[0] === 'playlist-remove') playlist.splice(Number(command[1]), 1);
if (command[0] === 'loadfile') {
playlist.splice(Number(command[3]), 0, { filename: String(command[1]), current: false });
}
if (command[0] === 'loadlist') {
const [, title, filename] = /#EXTINF:0,(.*)\n(.*)\n$/.exec(String(command[1])) ?? [];
playlist.splice(Number(command[3]), 0, { filename: filename!, current: false, title });
}
const titleIndex = /^playlist\/(\d+)\/title$/.exec(String(command[1]))?.[1];
if (command[0] === 'set_property' && titleIndex !== undefined) {
playlist[Number(titleIndex)]!.title = String(command[2]);
}
},
logDebug: () => {},
});
const playing = (itemId: string) => {
for (const item of playlist) item.current = item.filename === url(itemId);
if (!playlist.some((item) => item.current)) {
playlist.splice(0, playlist.length, { filename: url(itemId), current: true });
}
};
return {
queue,
commands,
playlist,
playing,
episodeListCalls: () => episodeListCalls,
setAfterRead: (callback: (() => void) | undefined) => {
afterRead = callback;
},
filenames: () => playlist.map((item) => item.filename),
titles: () => playlist.map((item) => item.title),
};
}
test('queueNeighbors inserts the episode window around the current entry', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), [url('e2'), url('e3'), url('e4')]);
assert.deepEqual(
harness.commands.filter((command) => command[0] === 'loadfile'),
[
['loadfile', url('e4'), 'insert-at', 1, 'start=e4'],
['loadfile', url('e2'), 'insert-at', 0, 'start=e2'],
],
);
const managedAt = harness.commands.findIndex(
(command) => command[1] === 'subminer-managed-playlist-entries',
);
assert.deepEqual(harness.commands[managedAt], [
'script-message',
'subminer-managed-playlist-entries',
url('e3'),
url('e4'),
url('e2'),
]);
assert.ok(
managedAt < harness.commands.findIndex((command) => command[0] === 'loadfile'),
'the plugin learns the managed paths before mpv can start an inserted entry',
);
assert.deepEqual(harness.titles(), ['Show e2', 'Show e3', 'Show e4']);
assert.equal(harness.queue.find(url('e4'))?.entry.itemId, 'e4');
assert.equal(harness.queue.find(url('e5')), null);
});
test('queueNeighbors slides the window when mpv moves to a queued episode', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
await harness.queue.queueNeighbors(null, entry('e4'));
assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]);
assert.deepEqual(harness.titles(), ['Show e3', 'Show e4', 'Show e5']);
assert.equal(harness.queue.find(url('e2')), null);
assert.equal(harness.episodeListCalls(), 1, 'series order is reused while navigating');
});
test('queueNeighbors keeps entries still in the window and edits only its far ends', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
const commandsBefore = harness.commands.length;
await harness.queue.queueNeighbors(null, entry('e4'));
assert.deepEqual(
harness.commands
.slice(commandsBefore)
.filter((command) => command[0] === 'loadfile' || command[0] === 'playlist-remove'),
[
['playlist-remove', 0],
['loadfile', url('e5'), 'insert-at', 2, 'start=e5'],
],
);
});
test('queueNeighbors never undoes a navigation that lands after its playlist read', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
// The read sees e4 playing; the user steps back to e3 before the edits arrive.
harness.setAfterRead(() => harness.playing('e3'));
await harness.queue.queueNeighbors(null, entry('e4'));
assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3'));
assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]);
});
test('queueNeighbors keeps the episode just left even with the smallest configured window', async () => {
const harness = makeHarness({ enabled: true, maxEpisodes: 2 });
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
// The read sees e4 playing; the user steps back to e3 before the edits arrive.
harness.setAfterRead(() => harness.playing('e3'));
await harness.queue.queueNeighbors(null, entry('e4'));
assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3'));
assert.ok(harness.filenames().includes(url('e3')));
});
test('queueNeighbors leaves the playlist alone once mpv has moved past the item', async () => {
const harness = makeHarness();
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
harness.playing('e4');
const before = harness.filenames();
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), before);
});
test('queueNeighbors drops queued entries and adds none when the playlist is disabled', async () => {
const settings = { enabled: true, maxEpisodes: 3 };
const harness = makeHarness(settings);
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
settings.enabled = false;
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), [url('e3')]);
});
test('reset cancels a queue run that is still resolving episodes', async () => {
const harness = makeHarness();
harness.playing('e3');
const pending = harness.queue.queueNeighbors(null, entry('e3'));
harness.queue.reset();
await pending;
assert.deepEqual(harness.filenames(), [url('e3')]);
assert.equal(harness.queue.find(url('e3')), null);
});
test('queueNeighbors titles entries through an m3u on mpv without writable playlist titles', async () => {
const harness = makeHarness(undefined, 'loadlist');
harness.playing('e3');
await harness.queue.queueNeighbors(null, entry('e3'));
assert.deepEqual(harness.filenames(), [url('e2'), url('e3'), url('e4')]);
assert.deepEqual(harness.titles(), ['Show e2', undefined, 'Show e4']);
assert.equal(
harness.commands.some((command) => command[0] === 'loadfile' || command[0] === 'set_property'),
false,
);
// The plugin hears each entry's options before mpv can start it.
const optionsAt = harness.commands.findIndex(
(command) => command[0] === 'script-message' && command[2] === url('e4'),
);
assert.deepEqual(harness.commands[optionsAt], [
'script-message',
'subminer-playlist-entry-options',
url('e4'),
'start',
'e4',
]);
assert.equal(harness.commands[optionsAt + 1]?.[0], 'loadlist');
});
test('buildMpvEntryLoadCommands keeps a title on one m3u line and quotes loadfile values', () => {
const titled = {
...entry('e1'),
title: 'A, B\nC',
fileOptions: [['force-media-title', 'A, B']] as const,
};
assert.deepEqual(buildMpvEntryLoadCommands(titled, 'loadlist', { kind: 'replace' })[1], [
'loadlist',
`memory://#EXTM3U\n#EXTINF:0,A, B C\n${url('e1')}\n`,
'replace',
]);
assert.deepEqual(buildMpvEntryLoadCommands(titled, 'loadfile', { kind: 'replace' }), [
['loadfile', url('e1'), 'replace', -1, 'force-media-title=%4%A, B'],
]);
});
test('chooseMpvEntryLoadMode uses loadlist only on mpv before 0.42 with the plugin hook', () => {
assert.equal(chooseMpvEntryLoadMode('mpv v0.41.0', true), 'loadlist');
assert.equal(chooseMpvEntryLoadMode('mpv v0.41.0', false), 'loadfile');
assert.equal(chooseMpvEntryLoadMode('mpv v0.42.0', true), 'loadfile');
assert.equal(chooseMpvEntryLoadMode('mpv v1.0.0', true), 'loadfile');
assert.equal(chooseMpvEntryLoadMode(null, true), 'loadfile');
});
@@ -0,0 +1,299 @@
/** What the episode playlist needs from a prepared Jellyfin item. */
export type JellyfinPlaylistEntry = {
itemId: string;
/** Set for episodes; the playlist only queues neighbors within a series. */
seriesId: string | null;
/** The URL handed to mpv, which mpv reports back as `path` when it starts the entry. */
playbackUrl: string;
/** Per-file mpv options as name/value pairs, applied whenever mpv starts this entry. */
fileOptions: ReadonlyArray<readonly [name: string, value: string]>;
/** Shown in mpv's playlist, which otherwise lists the stream URL and its API key. */
title: string;
};
/**
* How entries get into mpv's playlist with their title and per-file options.
* - `loadfile`: options ride on `loadfile`, and the title is set through `playlist/N/title`,
* which mpv accepts from 0.42.
* - `loadlist`: an in-memory m3u carries the title (`#EXTINF`), which older mpv shows too, and
* the SubMiner mpv plugin applies the options from its `on_load` hook.
*/
export type MpvEntryLoadMode = 'loadfile' | 'loadlist';
/** Set by the mpv plugin when its `on_load` hook applies `ENTRY_OPTIONS_SCRIPT_MESSAGE` options. */
export const PLUGIN_ENTRY_OPTIONS_USER_DATA = 'user-data/subminer/playlist-entry-options';
/** `<path> <name> <value> ...`: per-file options the mpv plugin applies when `path` loads. */
export const ENTRY_OPTIONS_SCRIPT_MESSAGE = 'subminer-playlist-entry-options';
/** Picks `loadlist` only where it is needed (mpv before 0.42) and the plugin can apply options. */
export function chooseMpvEntryLoadMode(
mpvVersion: unknown,
pluginAppliesEntryOptions: boolean,
): MpvEntryLoadMode {
const match = /(\d+)\.(\d+)/.exec(String(mpvVersion ?? ''));
if (!match || !pluginAppliesEntryOptions) return 'loadfile';
const [major, minor] = [Number(match[1]), Number(match[2])];
return major === 0 && minor < 42 ? 'loadlist' : 'loadfile';
}
// mpv's `%<bytes>%value` quoting takes any value verbatim, commas and colons included.
function formatLoadfileOptions(options: JellyfinPlaylistEntry['fileOptions']): string {
return options
.map(([name, value]) =>
/^[\w.-]*$/.test(value)
? `${name}=${value}`
: `${name}=%${Buffer.byteLength(value, 'utf8')}%${value}`,
)
.join(',');
}
type MpvPlaylistPlacement = { kind: 'replace' } | { kind: 'insert-at'; index: number };
/** The mpv commands that load `entry` with its title and options at `placement`. */
export function buildMpvEntryLoadCommands(
entry: JellyfinPlaylistEntry,
mode: MpvEntryLoadMode,
placement: MpvPlaylistPlacement,
): Array<Array<string | number>> {
if (mode === 'loadlist') {
const title = entry.title.replace(/[\r\n]+/g, ' ');
const m3u = `memory://#EXTM3U\n#EXTINF:0,${title}\n${entry.playbackUrl}\n`;
return [
[
'script-message',
ENTRY_OPTIONS_SCRIPT_MESSAGE,
entry.playbackUrl,
...entry.fileOptions.flat(),
],
placement.kind === 'replace'
? ['loadlist', m3u, 'replace']
: ['loadlist', m3u, 'insert-at', placement.index],
];
}
const options = formatLoadfileOptions(entry.fileOptions);
if (placement.kind === 'replace')
return [['loadfile', entry.playbackUrl, 'replace', -1, options]];
return [
['loadfile', entry.playbackUrl, 'insert-at', placement.index, options],
// Sent while the entry is still at that index.
['set_property', `playlist/${placement.index}/title`, entry.title],
];
}
export type JellyfinEpisodePlaylistSettings = {
enabled: boolean;
/** Most entries kept in mpv's playlist, the current one included. Raised to at least 3. */
maxEpisodes: number;
};
/**
* A window of 3 or more always holds the current episode's immediate neighbors (it only shifts
* at a series edge, where that neighbor does not exist). Removals then stay at least two steps
* from the playing entry, so a queue run cannot remove the episode a user just stepped back to.
*/
const MIN_WINDOW_EPISODES = 3;
export type JellyfinQueuedEpisode<Context, Entry> = {
context: Context;
entry: Entry;
};
/** Tells the mpv plugin which playlist entries the app starts itself, so it skips its own startup. */
export const MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE = 'subminer-managed-playlist-entries';
type MpvPlaylistItem = { filename: string; current: boolean };
function parseMpvPlaylist(raw: unknown): MpvPlaylistItem[] {
if (!Array.isArray(raw)) return [];
return raw.map((item: unknown) => {
const record = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
return {
filename: typeof record.filename === 'string' ? record.filename : '',
current: record.current === true,
};
});
}
/**
* Picks up to `maxEpisodes` ids around `currentId`, centered on it (an extra slot goes forward)
* and shifted inward at either end of the series so the window stays full.
*/
export function selectEpisodeWindow(
episodeIds: readonly string[],
currentId: string,
maxEpisodes: number,
): { previousIds: string[]; nextIds: string[] } {
const index = episodeIds.indexOf(currentId);
const size = Math.min(episodeIds.length, Math.max(1, Math.floor(maxEpisodes)));
if (index < 0 || size <= 1) return { previousIds: [], nextIds: [] };
const start = Math.min(Math.max(0, index - Math.floor((size - 1) / 2)), episodeIds.length - size);
return {
previousIds: episodeIds.slice(start, index),
nextIds: episodeIds.slice(index + 1, start + size),
};
}
/**
* Keeps the episodes around the playing Jellyfin item in mpv's playlist, so mpv's own playlist
* navigation (and end-of-file advance) moves through the series. mpv starts those entries by
* itself; `find` lets the playback handler recognize them from mpv's `path`.
*/
export function createJellyfinEpisodePlaylist<Context, Entry extends JellyfinPlaylistEntry>(deps: {
getSettings: () => JellyfinEpisodePlaylistSettings;
listSeriesEpisodeIds: (context: Context, seriesId: string) => Promise<string[]>;
prepareEntry: (context: Context, itemId: string) => Promise<Entry>;
readMpvPlaylist: () => Promise<unknown>;
/** The mode of the explicit playback this playlist follows. */
getEntryLoadMode: () => MpvEntryLoadMode;
sendMpvCommand: (command: Array<string | number>) => void;
logDebug: (message: string, error?: unknown) => void;
}) {
let queued = new Map<string, JellyfinQueuedEpisode<Context, Entry>>();
// Episode order per series, fetched once per explicit playback and reused while navigating.
let seriesEpisodeIds = new Map<string, Promise<string[]>>();
// Bumped by every reset and queue run, so a slow run never edits a playlist that moved on.
let generation = 0;
function getSeriesEpisodeIds(context: Context, seriesId: string): Promise<string[]> {
let ids = seriesEpisodeIds.get(seriesId);
if (!ids) {
ids = deps.listSeriesEpisodeIds(context, seriesId);
seriesEpisodeIds.set(seriesId, ids);
// A failed lookup is retried on the next queue run.
ids.catch(() => seriesEpisodeIds.delete(seriesId));
}
return ids;
}
async function prepareEntries(context: Context, itemIds: string[]): Promise<Map<string, Entry>> {
const prepared = new Map<string, Entry>();
await Promise.all(
itemIds.map((itemId) =>
deps.prepareEntry(context, itemId).then(
(entry) => {
prepared.set(itemId, entry);
},
(error: unknown) => {
deps.logDebug(`Failed to prepare Jellyfin episode ${itemId} for the playlist`, error);
},
),
),
);
return prepared;
}
async function queueNeighbors(context: Context, current: Entry): Promise<void> {
const run = ++generation;
const settings = deps.getSettings();
let windowIds = [current.itemId];
if (settings.enabled && current.seriesId) {
const episodeIds = await getSeriesEpisodeIds(context, current.seriesId);
const window = selectEpisodeWindow(
episodeIds,
current.itemId,
Math.max(MIN_WINDOW_EPISODES, settings.maxEpisodes),
);
windowIds = [...window.previousIds, current.itemId, ...window.nextIds];
}
// Entries already queued stay where they are, so only the missing ones are resolved.
const queuedItemIds = new Set([...queued.values()].map(({ entry }) => entry.itemId));
const prepared = await prepareEntries(
context,
windowIds.filter((itemId) => itemId !== current.itemId && !queuedItemIds.has(itemId)),
);
if (run !== generation) return;
const playlist = parseMpvPlaylist(await deps.readMpvPlaylist());
if (run !== generation) return;
const currentIndex = playlist.findIndex((item) => item.current);
// mpv already left this item, so the run that follows it owns the playlist.
if (playlist[currentIndex]?.filename !== current.playbackUrl) return;
// mpv may have moved on since the read, so this only touches entries outside the window
// and never removes one the user could have just navigated to. `model` mirrors mpv's
// playlist by item id (null for entries the app did not queue) as the commands edit it.
const model = playlist.map((item) =>
item.filename === current.playbackUrl
? current.itemId
: (queued.get(item.filename)?.entry.itemId ?? null),
);
for (let index = model.length - 1; index >= 0; index -= 1) {
const itemId = model[index];
if (itemId === null || itemId === undefined || windowIds.includes(itemId)) continue;
deps.sendMpvCommand(['playlist-remove', index]);
model.splice(index, 1);
}
const nextQueued = new Map<string, JellyfinQueuedEpisode<Context, Entry>>();
for (const queuedEpisode of queued.values()) {
if (model.includes(queuedEpisode.entry.itemId)) {
nextQueued.set(queuedEpisode.entry.playbackUrl, queuedEpisode);
}
}
nextQueued.set(current.playbackUrl, { context, entry: current });
const currentAt = windowIds.indexOf(current.itemId);
const nextIds = windowIds.slice(currentAt + 1);
const previousIds = windowIds.slice(0, currentAt).reverse();
// Every prepared entry is missing from mpv's playlist, so each one gets inserted below.
for (const itemId of [...nextIds, ...previousIds]) {
const entry = prepared.get(itemId);
if (entry) nextQueued.set(entry.playbackUrl, { context, entry });
}
queued = nextQueued;
// Sent before the inserts, so the plugin already knows an entry when mpv starts it.
deps.sendMpvCommand([
'script-message',
MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE,
...queued.keys(),
]);
const mode = deps.getEntryLoadMode();
const insertEntry = (entry: Entry, index: number) => {
for (const command of buildMpvEntryLoadCommands(entry, mode, { kind: 'insert-at', index })) {
deps.sendMpvCommand(command);
}
model.splice(index, 0, entry.itemId);
};
// A `loadlist` entry already has its title from the m3u.
if (mode === 'loadfile') {
deps.sendMpvCommand([
'set_property',
`playlist/${model.indexOf(current.itemId)}/title`,
current.title,
]);
}
// Walk outward from the current entry, inserting each missing episode beside its
// neighbor in the window.
let anchor = model.indexOf(current.itemId);
for (const itemId of nextIds) {
const entry = prepared.get(itemId);
if (model.includes(itemId)) anchor = model.indexOf(itemId);
else if (entry) insertEntry(entry, ++anchor);
}
anchor = model.indexOf(current.itemId);
for (const itemId of previousIds) {
const entry = prepared.get(itemId);
if (model.includes(itemId)) anchor = model.indexOf(itemId);
else if (entry) insertEntry(entry, anchor);
}
}
return {
/** Forgets queued entries and cancels queue runs in flight, for a new explicit playback. */
reset(): void {
generation += 1;
queued = new Map();
seriesEpisodeIds = new Map();
},
/** The queued episode whose playback URL mpv reports as `path`, if any. */
find(path: string): JellyfinQueuedEpisode<Context, Entry> | null {
return queued.get(path) ?? null;
},
/** Fills mpv's playlist with the episodes around `current`, mpv's current entry. */
queueNeighbors: (context: Context, current: Entry): Promise<void> =>
queueNeighbors(context, current).catch((error: unknown) => {
deps.logDebug('Failed to queue adjacent Jellyfin episodes', error);
}),
};
}
@@ -3,6 +3,10 @@ import test from 'node:test';
import type { JellyfinPlaybackPlan } from '../../core/services/jellyfin';
import type { JellyfinTimelinePlaybackState } from '../../core/services/jellyfin-playback-reporter';
import { createPlayJellyfinItemInMpvHandler } from './jellyfin-playback-launch';
import type {
ActiveJellyfinRemotePlaybackState,
JellyfinPlaybackReporterLike,
} from './jellyfin-remote-commands';
type Deps = Parameters<typeof createPlayJellyfinItemInMpvHandler>[0];
type PlayParams = Parameters<ReturnType<typeof createPlayJellyfinItemInMpvHandler>>[0];
@@ -30,6 +34,7 @@ function makePlan(overrides: Partial<JellyfinPlaybackPlan> = {}): JellyfinPlayba
title: 'Episode 1',
itemTitle: 'Episode 1',
seriesTitle: null,
seriesId: null,
seasonNumber: null,
episodeNumber: null,
startTimeTicks: 0,
@@ -49,11 +54,13 @@ function makeHarness(options: { plan?: Partial<JellyfinPlaybackPlan>; deps?: Par
const activeStates: Array<Parameters<Deps['setActivePlayback']>[0]> = [];
const reports: JellyfinTimelinePlaybackState[] = [];
const reporterParams: Array<Parameters<Deps['createPlaybackReporter']>[0]> = [];
const reporter = {
// A new reporter per playback, as in the app; the handler tells playbacks apart by it.
const reporters: JellyfinPlaybackReporterLike[] = [];
const createReporter = (): JellyfinPlaybackReporterLike => ({
reportPlaying: async (state: JellyfinTimelinePlaybackState) => void reports.push(state),
reportProgress: async () => {},
reportStopped: async () => {},
};
});
const handler = createPlayJellyfinItemInMpvHandler({
ensureMpvConnectedForPlayback: async () => true,
@@ -73,21 +80,33 @@ function makeHarness(options: { plan?: Partial<JellyfinPlaybackPlan>; deps?: Par
activeStates.push(state);
events.push(`active:${String(state.loadedMediaPath)}`);
},
getActivePlayback: () => activeStates.at(-1) ?? null,
setLastProgressAtMs: () => {},
createPlaybackReporter: (params) => {
reporterParams.push(params);
const reporter = createReporter();
reporters.push(reporter);
return reporter;
},
reportPlaybackSuperseded: async () => {},
waitForTransitionReports: async () => {},
trackPlaybackStart: () => {},
getEpisodePlaylistSettings: () => ({ enabled: true, maxEpisodes: 3 }),
listSeriesEpisodeIds: async () => [],
readMpvPlaylist: async () => [],
resolveEntryLoadMode: async () => 'loadfile',
showMpvOsd: () => {},
logDebug: () => {},
...options.deps,
});
return {
handler,
commands,
events,
activeStates,
reports,
reporter,
reporters,
reporterParams,
play: (params: Partial<PlayParams> = {}) =>
handler({
@@ -141,19 +160,18 @@ test('playback handler disables mpv subtitle selection, then loads media and rep
['set_property', 'sub-visibility', 'no'],
['set_property', 'secondary-sub-visibility', 'no'],
['script-message', 'subminer-managed-subtitles-loading'],
['set_property', 'force-media-title', 'Episode 1'],
[
'loadfile',
'https://stream.example/video.m3u8',
'replace',
-1,
`${SUPPRESSED_SUBTITLE_OPTIONS},start=1.2`,
`${SUPPRESSED_SUBTITLE_OPTIONS},start=1.2,force-media-title=%9%Episode 1`,
],
]);
assert.equal(harness.activeStates.length, 1);
assert.equal(harness.activeStates[0]?.playMethod, 'DirectPlay');
assert.equal(harness.activeStates[0]?.lastKnownPositionSeconds, 1.2);
assert.equal(harness.activeStates[0]?.reporter, harness.reporter);
assert.equal(harness.activeStates[0]?.reporter, harness.reporters[0]);
assert.deepEqual(harness.reporterParams, [{ session: baseSession, clientInfo: baseClientInfo }]);
assert.equal(harness.reports.length, 1);
assert.equal(harness.reports[0]?.eventName, 'start');
@@ -296,12 +314,39 @@ test('playback handler publishes Jellyfin title before loading tokenized stream
const loadIndex = harness.events.indexOf('cmd:loadfile');
assert.ok(titleIndex >= 0);
assert.ok(titleIndex < loadIndex);
const mpvTitleIndex = harness.commands.findIndex((command) => command[1] === 'force-media-title');
// mpv gets the title as a per-file option, so it never falls back to the URL.
assert.ok(
mpvTitleIndex >= 0 && mpvTitleIndex < harness.commands.findIndex((c) => c[0] === 'loadfile'),
String(harness.loadfile()?.[4]).endsWith(
',force-media-title=%30%Galaxy Quest S02E07 A New Hope',
),
);
});
test('playback handler loads a titled m3u when mpv cannot set playlist titles', async () => {
const harness = makeHarness({
plan: { startTimeTicks: 12_000_000 },
deps: { resolveEntryLoadMode: async () => 'loadlist' },
});
await harness.play();
assert.equal(harness.loadfile(), undefined);
assert.deepEqual(harness.commands.slice(-2), [
[
'script-message',
'subminer-playlist-entry-options',
'https://stream.example/video.m3u8',
...['sid', 'no', 'secondary-sid', 'no', 'sub-auto', 'no', 'sub-visibility', 'no'],
...['secondary-sub-visibility', 'no', 'start', '1.2', 'force-media-title', 'Episode 1'],
],
[
'loadlist',
'memory://#EXTM3U\n#EXTINF:0,Episode 1\nhttps://stream.example/video.m3u8\n',
'replace',
],
]);
});
test('playback handler arms unloaded active playback before loading mpv media', async () => {
const harness = makeHarness();
@@ -355,7 +400,217 @@ for (const c of HOOK_FAILURE_CASES) {
'https://stream.example/video.m3u8',
'replace',
-1,
SUPPRESSED_SUBTITLE_OPTIONS,
`${SUPPRESSED_SUBTITLE_OPTIONS},force-media-title=%9%Episode 1`,
]);
});
}
/**
* A series of three episodes where `item-1` plays first. mpv's playlist and the active playback
* follow the commands the handler sends, the way mpv and the Jellyfin assembly would.
*/
function makeSeriesHarness() {
const streamUrl = (itemId: string) => `https://jf.example/Videos/${itemId}/stream`;
const playlist: Array<{ filename: string; current: boolean }> = [];
const statsMetadata: Array<{ itemId: string }> = [];
const superseded: string[] = [];
const startsTracked: string[] = [];
let active: ActiveJellyfinRemotePlaybackState | null = null;
// Stop reports in flight, from the superseded handler or `startGenericStop`.
const stopsInFlight = new Set<Promise<void>>();
const pendingSupersededStops: Array<() => void> = [];
const trackStop = () => {
let release = () => {};
const stop = new Promise<void>((resolve) => {
release = resolve;
});
stopsInFlight.add(stop);
void stop.then(() => stopsInFlight.delete(stop));
pendingSupersededStops.push(release);
return stop;
};
const harness = makeHarness({
deps: {
resolvePlaybackPlan: async ({ itemId }) =>
makePlan({
url: streamUrl(itemId),
title: `${itemId}: 前編, 1`,
seriesId: 'series-1',
}),
listSeriesEpisodeIds: async () => ['item-0', 'item-1', 'item-2'],
readMpvPlaylist: async () => playlist.map((item) => ({ ...item })),
getActivePlayback: () => active,
setActivePlayback: (state) => {
active = { ...state };
},
reportPlaybackSuperseded: (playback) => {
superseded.push(playback.itemId);
return trackStop();
},
trackPlaybackStart: (_report, playback) => void startsTracked.push(playback.itemId),
waitForTransitionReports: async () => {
while (stopsInFlight.size > 0) await Promise.all([...stopsInFlight]);
},
recordJellyfinPlaybackMetadata: (metadata) => void statsMetadata.push(metadata),
},
});
const sendMpvCommand = harness.commands.push.bind(harness.commands);
harness.commands.push = (...commands) => {
for (const command of commands) {
if (command[0] === 'loadfile' && command[2] === 'replace') {
playlist.splice(0, playlist.length, { filename: String(command[1]), current: true });
} else if (command[0] === 'loadfile') {
playlist.splice(Number(command[3]), 0, { filename: String(command[1]), current: false });
}
}
return sendMpvCommand(...commands);
};
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
return {
...harness,
streamUrl,
playlist,
statsMetadata,
superseded,
startsTracked,
active: () => active,
// Completes the oldest stop report still in flight.
releaseSupersededStop: () => pendingSupersededStops.shift()?.(),
// The generic stop handler, run when mpv reports an empty path between files: it clears
// the active playback and reports its stop on its own.
startGenericStop: () => {
active = null;
void trackStop();
},
// What the Jellyfin assembly does with each new mpv path.
mpvPathChanged: (path: string) => {
if (harness.handler.adoptQueuedEpisode(path)) return;
if (active) active.loadedMediaPath = path;
},
flush,
};
}
test('playback handler queues neighbor episodes only once mpv plays the item', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.handler.handlePlaybackTimePos();
await harness.flush();
assert.equal(harness.playlist.length, 1, 'nothing is queued before mpv reports the item');
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
assert.deepEqual(
harness.playlist.map((item) => item.filename),
[harness.streamUrl('item-0'), harness.streamUrl('item-1'), harness.streamUrl('item-2')],
);
const queuedNext = harness.commands.find(
(command) => command[0] === 'loadfile' && command[1] === harness.streamUrl('item-2'),
);
assert.deepEqual(queuedNext, [
'loadfile',
harness.streamUrl('item-2'),
'insert-at',
1,
`${SUPPRESSED_SUBTITLE_OPTIONS},force-media-title=%17%item-2: 前編, 1`,
]);
});
test('playback handler takes over a queued episode mpv starts from its playlist', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
const commandsBefore = harness.commands.length;
harness.mpvPathChanged(harness.streamUrl('item-2'));
// Synchronous, so the immersion tracker that runs next already sees the episode's metadata.
assert.deepEqual(
harness.statsMetadata.map((metadata) => metadata.itemId),
['item-1', 'item-2'],
);
assert.equal(harness.active()?.itemId, 'item-2');
assert.equal(harness.active()?.loadedMediaPath, harness.streamUrl('item-2'));
assert.equal(
harness.commands.slice(commandsBefore).some((command) => command[2] === 'replace'),
false,
'mpv already loads the entry, so the handler must not load it again',
);
await harness.flush();
assert.deepEqual(harness.superseded, ['item-1']);
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1'],
'the new start waits for the previous stop',
);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1', 'item-2'],
);
assert.deepEqual(harness.startsTracked, ['item-1', 'item-2'], 'each start is tracked');
assert.equal(harness.handler.adoptQueuedEpisode(harness.streamUrl('item-2')), false);
assert.equal(harness.handler.adoptQueuedEpisode('https://elsewhere.example/video.mkv'), false);
});
test('playback handler starts an episode only after every stop in flight and skips switched-away ones', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
harness.mpvPathChanged(harness.streamUrl('item-2'));
harness.mpvPathChanged(harness.streamUrl('item-1'));
await harness.flush();
assert.deepEqual(harness.superseded, ['item-1', 'item-2']);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1'],
'the start waits for the stop still in flight',
);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1', 'item-1'],
'the skipped-over episode never reports playing; the one mpv returned to does',
);
});
test('playback handler waits for a stop the empty path between files triggered', async () => {
const harness = makeSeriesHarness();
await harness.play({ itemId: 'item-1' });
harness.mpvPathChanged(harness.streamUrl('item-1'));
harness.handler.handlePlaybackTimePos();
await harness.flush();
// Past the startup grace, mpv's empty path stops item-1 before item-2's path arrives.
harness.startGenericStop();
harness.mpvPathChanged(harness.streamUrl('item-2'));
await harness.flush();
assert.deepEqual(harness.superseded, [], 'nothing was active to supersede');
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1'],
);
harness.releaseSupersededStop();
await harness.flush();
assert.deepEqual(
harness.reports.map((report) => report.itemId),
['item-1', 'item-2'],
);
});
+297 -88
View File
@@ -1,7 +1,17 @@
import type { JellyfinAuthSession, JellyfinPlaybackPlan } from '../../core/services/jellyfin';
import type { JellyfinConfig } from '../../types';
import type { MpvRuntimeClientLike } from '../../core/services/mpv';
import type { JellyfinPlaybackReporterLike } from './jellyfin-remote-commands';
import {
buildMpvEntryLoadCommands,
createJellyfinEpisodePlaylist,
type JellyfinEpisodePlaylistSettings,
type JellyfinPlaylistEntry,
type MpvEntryLoadMode,
} from './jellyfin-episode-playlist';
import type {
ActiveJellyfinRemotePlaybackState,
JellyfinPlaybackReporterLike,
} from './jellyfin-remote-commands';
type JellyfinClientInfo = {
clientName: string;
@@ -9,6 +19,12 @@ type JellyfinClientInfo = {
deviceId: string;
};
type JellyfinPlaybackContext = {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
jellyfinConfig: JellyfinConfig;
};
type ActivePlaybackState = {
itemId: string;
reporter: JellyfinPlaybackReporterLike;
@@ -31,13 +47,13 @@ export type JellyfinPlaybackStatsMetadata = {
itemId: string;
};
const JELLYFIN_LOADFILE_SUBTITLE_SUPPRESSION_OPTIONS = [
'sid=no',
'secondary-sid=no',
'sub-auto=no',
'sub-visibility=no',
'secondary-sub-visibility=no',
];
const JELLYFIN_SUBTITLE_SUPPRESSION_OPTIONS = [
['sid', 'no'],
['secondary-sid', 'no'],
['sub-auto', 'no'],
['sub-visibility', 'no'],
['secondary-sub-visibility', 'no'],
] as const;
function runBestEffortPlaybackHook(callback: () => void | Promise<void>): void {
try {
@@ -104,14 +120,91 @@ function resolveEffectiveStartTimeTicks(
return Math.max(0, planStartTimeTicks);
}
function buildJellyfinLoadfileOptions(plan: JellyfinPlaybackPlan, startSeconds: number): string {
const options = [...JELLYFIN_LOADFILE_SUBTITLE_SUPPRESSION_OPTIONS];
if (plan.mode === 'direct' && startSeconds > 0) {
options.push(`start=${startSeconds}`);
}
return options.join(',');
/** A resolved Jellyfin item in the form mpv loads it. */
type JellyfinPreparedPlayback = {
itemId: string;
seriesId: string | null;
title: string;
plan: JellyfinPlaybackPlan;
playbackUrl: string;
fileOptions: JellyfinPlaylistEntry['fileOptions'];
startTimeTicks: number;
startSeconds: number;
playMethod: 'DirectPlay' | 'Transcode';
};
// The title is a per-file option, so mpv never shows the tokenized stream URL as the title, and
// no global title is left behind for the next playlist entry to fall back to.
function buildJellyfinFileOptions(
plan: JellyfinPlaybackPlan,
startSeconds: number,
): JellyfinPlaylistEntry['fileOptions'] {
return [
...JELLYFIN_SUBTITLE_SUPPRESSION_OPTIONS,
...(plan.mode === 'direct' && startSeconds > 0
? [['start', String(startSeconds)] as const]
: []),
['force-media-title', plan.title],
];
}
function prepareJellyfinPlayback(
itemId: string,
plan: JellyfinPlaybackPlan,
convertTicksToSeconds: (ticks: number) => number,
options: {
startTimeTicksOverride?: number;
fallbackToPlanStartTimeOnZeroOverride?: boolean;
} = {},
): JellyfinPreparedPlayback {
const startTimeTicks = resolveEffectiveStartTimeTicks(
plan.startTimeTicks,
options.startTimeTicksOverride,
options.fallbackToPlanStartTimeOnZeroOverride,
);
const startSeconds = startTimeTicks > 0 ? Math.max(0, convertTicksToSeconds(startTimeTicks)) : 0;
const playbackUrlBase =
plan.mode === 'direct'
? stripStartTimeTicksFromPlaybackUrl(plan.url)
: applyStartTimeTicksToPlaybackUrl(plan.url, startTimeTicks);
return {
itemId,
seriesId: plan.seriesId,
title: plan.title,
plan,
playbackUrl: stripManagedSubtitleStreamFromPlaybackUrl(playbackUrlBase),
fileOptions: buildJellyfinFileOptions(plan, startSeconds),
startTimeTicks,
startSeconds,
playMethod: plan.mode === 'direct' ? 'DirectPlay' : 'Transcode',
};
}
export type PlayJellyfinItemInMpvHandler = ((params: {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
jellyfinConfig: JellyfinConfig;
itemId: string;
audioStreamIndex?: number | null;
subtitleStreamIndex?: number | null;
startTimeTicksOverride?: number;
fallbackToPlanStartTimeOnZeroOverride?: boolean;
setQuitOnDisconnectArm?: boolean;
}) => Promise<void>) & {
/**
* Takes over a queued neighbor episode that mpv started from its playlist, given mpv's new
* `path`. Returns false when the path is not one, or is already the active playback. Runs
* synchronously up to recording stats metadata, so call it before the immersion tracker sees
* the path.
*/
adoptQueuedEpisode: (path: string) => boolean;
/**
* Called on mpv time-pos updates. The first one for a just-started item queues its neighbor
* episodes, so that work never competes with opening the stream.
*/
handlePlaybackTimePos: () => void;
};
export function createPlayJellyfinItemInMpvHandler(deps: {
ensureMpvConnectedForPlayback: () => Promise<boolean>;
getMpvClient: () => MpvRuntimeClientLike | null;
@@ -134,6 +227,7 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
clientInfo: JellyfinClientInfo;
itemId: string;
}) => void | Promise<void>;
getActivePlayback: () => ActiveJellyfinRemotePlaybackState | null;
setActivePlayback: (state: ActivePlaybackState) => void;
setLastProgressAtMs: (value: number) => void;
// Reports go out as the device and account that started this playback, for CLI play and
@@ -142,23 +236,146 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
}) => JellyfinPlaybackReporterLike;
/** Reports the stop of a playback mpv left for a queued neighbor episode. */
reportPlaybackSuperseded: (playback: ActiveJellyfinRemotePlaybackState) => Promise<void>;
/** Resolves once no Jellyfin episode start or stop report is in flight, whoever sent it. */
waitForTransitionReports: () => Promise<void>;
/** Tracks a start report, so the playback's own stop and later starts wait for it. */
trackPlaybackStart: (report: Promise<void>, playback: ActiveJellyfinRemotePlaybackState) => void;
/** Read on every queue run, so edits apply from the next episode change. */
getEpisodePlaylistSettings: () => JellyfinEpisodePlaylistSettings;
listSeriesEpisodeIds: (params: {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
seriesId: string;
}) => Promise<string[]>;
readMpvPlaylist: () => Promise<unknown>;
/** Asked once per explicit playback; its episode playlist keeps that mode. */
resolveEntryLoadMode: () => Promise<MpvEntryLoadMode>;
showMpvOsd: (text: string) => void;
recordJellyfinPlaybackMetadata?: (
metadata: JellyfinPlaybackStatsMetadata,
) => void | Promise<void>;
updateCurrentMediaTitle?: (title: string) => void | Promise<void>;
}) {
return async (params: {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
jellyfinConfig: JellyfinConfig;
itemId: string;
audioStreamIndex?: number | null;
subtitleStreamIndex?: number | null;
startTimeTicksOverride?: number;
fallbackToPlanStartTimeOnZeroOverride?: boolean;
setQuitOnDisconnectArm?: boolean;
}): Promise<void> => {
logDebug: (message: string, error?: unknown) => void;
}): PlayJellyfinItemInMpvHandler {
let entryLoadMode: MpvEntryLoadMode = 'loadfile';
const episodePlaylist = createJellyfinEpisodePlaylist<
JellyfinPlaybackContext,
JellyfinPreparedPlayback
>({
getSettings: () => deps.getEpisodePlaylistSettings(),
listSeriesEpisodeIds: (context, seriesId) =>
deps.listSeriesEpisodeIds({
session: context.session,
clientInfo: context.clientInfo,
seriesId,
}),
prepareEntry: async (context, itemId) =>
prepareJellyfinPlayback(
itemId,
await deps.resolvePlaybackPlan({ ...context, itemId }),
deps.convertTicksToSeconds,
),
readMpvPlaylist: () => deps.readMpvPlaylist(),
getEntryLoadMode: () => entryLoadMode,
sendMpvCommand: (command) => deps.sendMpvCommand(command),
logDebug: (message, error) => deps.logDebug(message, error),
});
// Records stats metadata and makes `prepared` the active playback. Synchronous, so a caller
// reacting to mpv's path change finishes it before the immersion tracker sees that path.
const beginPlayback = (
context: JellyfinPlaybackContext,
prepared: JellyfinPreparedPlayback,
loadedMediaPath: string | null,
): JellyfinPlaybackReporterLike => {
const { plan } = prepared;
runBestEffortPlaybackHook(() => deps.updateCurrentMediaTitle?.(plan.title));
runBestEffortPlaybackHook(() =>
deps.recordJellyfinPlaybackMetadata?.({
mediaPath: prepared.playbackUrl,
displayTitle: plan.title,
itemTitle: plan.itemTitle,
seriesTitle: plan.seriesTitle,
seasonNumber: plan.seasonNumber,
episodeNumber: plan.episodeNumber,
itemId: prepared.itemId,
}),
);
const reporter = deps.createPlaybackReporter({
session: context.session,
clientInfo: context.clientInfo,
});
deps.setActivePlayback({
itemId: prepared.itemId,
reporter,
mediaSourceId: undefined,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
playMethod: prepared.playMethod,
loadedMediaPath,
lastKnownPositionSeconds: prepared.startSeconds > 0 ? prepared.startSeconds : undefined,
});
deps.setLastProgressAtMs(0);
return reporter;
};
// The item whose neighbors get queued once mpv reports it playing.
let pendingNeighborQueue: {
context: JellyfinPlaybackContext;
prepared: JellyfinPreparedPlayback;
} | null = null;
// Runs once mpv has the item: subtitles, overlay, and the Jellyfin start report. Its
// neighbors are queued later, from the first time-pos update.
const finishPlaybackStartup = async (
context: JellyfinPlaybackContext,
prepared: JellyfinPreparedPlayback,
reporter: JellyfinPlaybackReporterLike,
): Promise<void> => {
const { plan } = prepared;
// Each start makes a new reporter, so it identifies this playback even when the same
// episode comes back. A later switch that took over does its own reporting.
const ownsPlayback = () => deps.getActivePlayback()?.reporter === reporter;
await awaitBestEffortPlaybackHook(() =>
deps.preloadExternalSubtitles({
session: context.session,
clientInfo: context.clientInfo,
itemId: prepared.itemId,
}),
);
if (!ownsPlayback()) return;
deps.showVisibleOverlay();
pendingNeighborQueue = { context, prepared };
// Jellyfin clears a session's now-playing item on any stop and keeps whichever start lands
// last, so this start waits for every start and stop in flight, including the generic stop
// mpv's empty path between files can trigger.
await deps.waitForTransitionReports();
const playback = deps.getActivePlayback();
if (playback?.reporter !== reporter) return;
const started = reporter.reportPlaying({
itemId: prepared.itemId,
mediaSourceId: undefined,
playMethod: prepared.playMethod,
positionTicks: prepared.startTimeTicks,
isPaused: false,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
eventName: 'start',
});
deps.trackPlaybackStart(
started.then(
() => undefined,
(error: unknown) => deps.logDebug('Failed to report Jellyfin playback start', error),
),
playback,
);
deps.showMpvOsd(`Jellyfin ${plan.mode}: ${plan.title}`);
};
const play = async (params: Parameters<PlayJellyfinItemInMpvHandler>[0]): Promise<void> => {
const connected = await deps.ensureMpvConnectedForPlayback();
const mpvClient = deps.getMpvClient();
if (!connected || !mpvClient) {
@@ -176,80 +393,72 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
subtitleStreamIndex: params.subtitleStreamIndex,
});
entryLoadMode = await deps.resolveEntryLoadMode().catch((error: unknown) => {
deps.logDebug('Failed to detect how mpv takes playlist titles', error);
return 'loadfile' as const;
});
deps.applyJellyfinMpvDefaults(mpvClient);
deps.sendMpvCommand(['set_property', 'sub-auto', 'no']);
deps.sendMpvCommand(['set_property', 'sid', 'no']);
deps.sendMpvCommand(['set_property', 'secondary-sid', 'no']);
deps.sendMpvCommand(['set_property', 'sub-visibility', 'no']);
deps.sendMpvCommand(['set_property', 'secondary-sub-visibility', 'no']);
const startTimeTicks = resolveEffectiveStartTimeTicks(
plan.startTimeTicks,
params.startTimeTicksOverride,
params.fallbackToPlanStartTimeOnZeroOverride,
);
const startSeconds =
startTimeTicks > 0 ? Math.max(0, deps.convertTicksToSeconds(startTimeTicks)) : 0;
const playbackUrlBase =
plan.mode === 'direct'
? stripStartTimeTicksFromPlaybackUrl(plan.url)
: applyStartTimeTicksToPlaybackUrl(plan.url, startTimeTicks);
const playbackUrl = stripManagedSubtitleStreamFromPlaybackUrl(playbackUrlBase);
const loadfileOptions = buildJellyfinLoadfileOptions(plan, startSeconds);
const playMethod = plan.mode === 'direct' ? 'DirectPlay' : 'Transcode';
runBestEffortPlaybackHook(() => deps.updateCurrentMediaTitle?.(plan.title));
runBestEffortPlaybackHook(() =>
deps.recordJellyfinPlaybackMetadata?.({
mediaPath: playbackUrl,
displayTitle: plan.title,
itemTitle: plan.itemTitle,
seriesTitle: plan.seriesTitle,
seasonNumber: plan.seasonNumber,
episodeNumber: plan.episodeNumber,
itemId: params.itemId,
}),
);
const reporter = deps.createPlaybackReporter({
const prepared = prepareJellyfinPlayback(params.itemId, plan, deps.convertTicksToSeconds, {
startTimeTicksOverride: params.startTimeTicksOverride,
fallbackToPlanStartTimeOnZeroOverride: params.fallbackToPlanStartTimeOnZeroOverride,
});
const context: JellyfinPlaybackContext = {
session: params.session,
clientInfo: params.clientInfo,
});
deps.setActivePlayback({
itemId: params.itemId,
reporter,
mediaSourceId: undefined,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
playMethod,
loadedMediaPath: null,
lastKnownPositionSeconds: startSeconds > 0 ? startSeconds : undefined,
});
deps.setLastProgressAtMs(0);
jellyfinConfig: params.jellyfinConfig,
};
// Replacing mpv's playlist takes the old neighbors with it.
episodePlaylist.reset();
pendingNeighborQueue = null;
const reporter = beginPlayback(context, prepared, null);
deps.sendMpvCommand(['script-message', 'subminer-managed-subtitles-loading']);
// Set mpv's title before loadfile can emit a URL-derived media-title event.
deps.sendMpvCommand(['set_property', 'force-media-title', plan.title]);
deps.sendMpvCommand(['loadfile', playbackUrl, 'replace', -1, loadfileOptions]);
for (const command of buildMpvEntryLoadCommands(prepared, entryLoadMode, { kind: 'replace' })) {
deps.sendMpvCommand(command);
}
if (params.setQuitOnDisconnectArm !== false) {
deps.armQuitOnDisconnect();
}
await awaitBestEffortPlaybackHook(() =>
deps.preloadExternalSubtitles({
session: params.session,
clientInfo: params.clientInfo,
itemId: params.itemId,
}),
);
deps.showVisibleOverlay();
void reporter.reportPlaying({
itemId: params.itemId,
mediaSourceId: undefined,
playMethod,
positionTicks: startTimeTicks,
isPaused: false,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
eventName: 'start',
});
deps.showMpvOsd(`Jellyfin ${plan.mode}: ${plan.title}`);
await finishPlaybackStartup(context, prepared, reporter);
};
const adoptQueuedEpisode = (path: string): boolean => {
const queued = episodePlaylist.find(path);
if (!queued) return false;
const previous = deps.getActivePlayback();
if (previous?.itemId === queued.entry.itemId) return false;
const reporter = beginPlayback(queued.context, queued.entry, path);
if (previous) {
void deps.reportPlaybackSuperseded(previous).catch((error: unknown) => {
deps.logDebug('Failed to report the previous Jellyfin episode stopped', error);
});
}
void finishPlaybackStartup(queued.context, queued.entry, reporter).catch((error: unknown) => {
deps.logDebug('Failed to start the queued Jellyfin episode', error);
});
return true;
};
const handlePlaybackTimePos = (): void => {
const pending = pendingNeighborQueue;
if (!pending) return;
const active = deps.getActivePlayback();
// time-pos can still belong to the file mpv is leaving until it reports the new path.
if (
active?.itemId !== pending.prepared.itemId ||
active.loadedMediaPath !== pending.prepared.playbackUrl
) {
return;
}
pendingNeighborQueue = null;
void episodePlaylist.queueNeighbors(pending.context, pending.prepared);
};
return Object.assign(play, { adoptQueuedEpisode, handlePlaybackTimePos });
}
@@ -5,6 +5,7 @@ import {
createJellyfinRemoteReportTracker,
createReportJellyfinRemoteProgressHandler,
createReportJellyfinRemoteStoppedHandler,
createReportSupersededJellyfinPlaybackHandler,
secondsToJellyfinTicks,
shouldAutoLoadSecondarySubTrackForJellyfinPlayback,
} from './jellyfin-remote-playback';
@@ -233,6 +234,7 @@ test('createReportJellyfinRemoteStoppedHandler reports stop and clears playback'
makePlayback({
itemId: 'item-2',
playMethod: 'Transcode',
loadedMediaPath: 'https://stream.example/item-2.m3u8',
reporter: makeReporter({
reportStopped: async (payload) => {
stoppedPayload = {
@@ -248,6 +250,7 @@ test('createReportJellyfinRemoteStoppedHandler reports stop and clears playback'
},
getMpvClient: () => ({
currentTimePos: 12.5,
currentVideoPath: 'https://stream.example/item-2.m3u8',
requestProperty: async () => {
throw new Error('unloaded');
},
@@ -264,6 +267,33 @@ test('createReportJellyfinRemoteStoppedHandler reports stop and clears playback'
assert.equal(cleared, true);
});
test('createReportJellyfinRemoteStoppedHandler ignores the position of a file mpv moved on to', async () => {
let stoppedTicks: number | undefined;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
makeStoppedDeps({
getActivePlayback: () =>
makePlayback({
itemId: 'item-1',
loadedMediaPath: 'https://stream.example/item-1.m3u8',
lastKnownPositionSeconds: 1410,
reporter: makeReporter({
reportStopped: async (payload) => {
stoppedTicks = payload.positionTicks;
},
}),
}),
getMpvClient: () => ({
currentTimePos: 42,
currentVideoPath: 'https://stream.example/item-2.m3u8',
}),
}),
);
await reportStopped();
assert.equal(stoppedTicks, 14_100_000_000);
});
test('createReportJellyfinRemoteStoppedHandler clears aborted playback that never loaded', async () => {
let cleared = false;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
@@ -289,6 +319,32 @@ test('createReportJellyfinRemoteStoppedHandler clears aborted playback that neve
assert.equal(cleared, true);
});
test('createReportJellyfinRemoteStoppedHandler keeps unloaded playback armed while the previous file unloads', async () => {
let cleared = false;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
makeStoppedDeps({
getActivePlayback: () =>
makePlayback({
loadedMediaPath: null,
stopReportsAfterMs: 10_000,
reporter: makeReporter({
reportStopped: async () => {
throw new Error('should not report stopped for unloaded media');
},
}),
}),
clearActivePlayback: () => {
cleared = true;
},
getNow: () => 5_000,
}),
);
await reportStopped();
assert.equal(cleared, false);
});
test('createReportJellyfinRemoteStoppedHandler uses cached position after mpv unload reset', async () => {
let cleared = false;
const calls: Array<{ event: string; positionTicks?: number }> = [];
@@ -445,3 +501,68 @@ test('createReportJellyfinRemoteStoppedHandler clears playback before reporting
'stopped:cleared',
]);
});
test('createReportSupersededJellyfinPlaybackHandler waits only for the superseded playback reports', async () => {
const events: string[] = [];
const tracker = createJellyfinRemoteReportTracker();
const superseded = makePlayback({
itemId: 'item-1',
lastKnownPositionSeconds: 1410,
reporter: makeReporter({
reportStopped: async (payload) => {
events.push(`stopped:${payload.itemId}@${payload.positionTicks}`);
},
}),
});
let finishOldProgress = () => {};
tracker.track(
new Promise<void>((resolve) => {
finishOldProgress = () => {
events.push('old progress done');
resolve();
};
}),
superseded,
);
// The new episode's progress stays in flight for the whole test.
tracker.track(new Promise<void>(() => {}), makePlayback({ itemId: 'item-2' }));
const reportSuperseded = createReportSupersededJellyfinPlaybackHandler({
ticksPerSecond: TICKS_PER_SECOND,
logDebug: () => {},
reportTracker: tracker,
});
const reported = reportSuperseded(superseded);
await Promise.resolve();
assert.deepEqual(events, [], 'the stop waits for its own progress already in flight');
finishOldProgress();
await reported;
assert.deepEqual(events, ['old progress done', 'stopped:item-1@14100000000']);
});
test('createReportJellyfinRemoteStoppedHandler is not held by reports for another playback', async () => {
const tracker = createJellyfinRemoteReportTracker();
// The next episode's progress stays in flight for the whole test.
tracker.track(new Promise<void>(() => {}), makePlayback({ itemId: 'item-2' }));
let stopped = false;
const reportStopped = createReportJellyfinRemoteStoppedHandler(
makeStoppedDeps({
getActivePlayback: () =>
makePlayback({
loadedMediaPath: 'https://stream.example/item-1.m3u8',
lastKnownPositionSeconds: 30,
reporter: makeReporter({
reportStopped: async () => {
stopped = true;
},
}),
}),
reportTracker: tracker,
}),
);
await reportStopped();
assert.equal(stopped, true);
});
+103 -52
View File
@@ -2,6 +2,7 @@ import type { ActiveJellyfinRemotePlaybackState } from './jellyfin-remote-comman
type MpvClientLike = {
currentTimePos?: number;
currentVideoPath?: string;
requestProperty?: (name: string) => Promise<unknown>;
};
@@ -112,22 +113,26 @@ function isSeekLikePositionJump(
// Jellyfin re-creates a session's NowPlayingItem from any progress report, so a progress
// tick that lands after the stop report leaves the server showing playback forever. The
// tracker lets the stop handler wait for reports that are already in flight.
// tracker lets the stop handler wait for reports that are already in flight. Each report is
// tagged with the playback it describes, so stopping one playback can skip another's reports.
export type JellyfinRemoteReportTracker = {
track: (report: Promise<void>) => void;
settled: () => Promise<void>;
track: (report: Promise<void>, playback: ActiveJellyfinRemotePlaybackState | null) => void;
/** Waits for in-flight reports: every one, or only those tagged with `playback`. */
settled: (playback?: ActiveJellyfinRemotePlaybackState) => Promise<void>;
};
export function createJellyfinRemoteReportTracker(): JellyfinRemoteReportTracker {
const active = new Set<Promise<void>>();
const active = new Map<Promise<void>, ActiveJellyfinRemotePlaybackState | null>();
const pending = (playback?: ActiveJellyfinRemotePlaybackState) =>
[...active].filter(([, owner]) => !playback || owner === playback).map(([report]) => report);
return {
track: (report) => {
active.add(report);
track: (report, playback) => {
active.set(report, playback);
void report.finally(() => active.delete(report));
},
settled: async () => {
while (active.size > 0) {
await Promise.allSettled([...active]);
settled: async (playback) => {
for (let reports = pending(playback); reports.length > 0; reports = pending(playback)) {
await Promise.allSettled(reports);
}
},
};
@@ -151,8 +156,10 @@ export function createReportJellyfinRemoteProgressHandler(
) {
let lastReportedPositionSeconds: number | null = null;
const report = async (force: boolean): Promise<void> => {
const playback = deps.getActivePlayback();
const report = async (
playback: ActiveJellyfinRemotePlaybackState | null,
force: boolean,
): Promise<void> => {
if (!playback) return;
const now = deps.getNow();
try {
@@ -191,8 +198,9 @@ export function createReportJellyfinRemoteProgressHandler(
};
return async (force = false): Promise<void> => {
const pending = report(force);
deps.reportTracker?.track(pending);
const playback = deps.getActivePlayback();
const pending = report(playback, force);
deps.reportTracker?.track(pending, playback);
await pending;
};
}
@@ -208,58 +216,101 @@ export type JellyfinRemoteStoppedReporterDeps = {
reportTracker?: JellyfinRemoteReportTracker;
};
type JellyfinStopReportDeps = {
ticksPerSecond: number;
logDebug: (message: string, error: unknown) => void;
logWarn?: (message: string) => void;
};
async function sendJellyfinStopReports(
deps: JellyfinStopReportDeps,
playback: ActiveJellyfinRemotePlaybackState,
positionSeconds: number,
): Promise<void> {
const positionTicks = secondsToJellyfinTicks(positionSeconds, deps.ticksPerSecond);
try {
await playback.reporter.reportProgress({
itemId: playback.itemId,
mediaSourceId: playback.mediaSourceId,
positionTicks,
isPaused: false,
playMethod: playback.playMethod,
audioStreamIndex: playback.audioStreamIndex,
subtitleStreamIndex: playback.subtitleStreamIndex,
eventName: 'TimeUpdate',
});
} catch (error) {
deps.logDebug('Failed to report Jellyfin remote final progress', error);
}
const reported = await playback.reporter.reportStopped({
itemId: playback.itemId,
mediaSourceId: playback.mediaSourceId,
positionTicks,
failed: false,
playMethod: playback.playMethod,
audioStreamIndex: playback.audioStreamIndex,
subtitleStreamIndex: playback.subtitleStreamIndex,
eventName: 'stop',
});
if (reported === false) {
deps.logWarn?.(
`Jellyfin did not accept the playback stop report for item ${playback.itemId}; the server may keep showing it as playing.`,
);
}
}
export function createReportJellyfinRemoteStoppedHandler(deps: JellyfinRemoteStoppedReporterDeps) {
return async (): Promise<void> => {
const playback = deps.getActivePlayback();
if (!playback) return;
if (playback.loadedMediaPath === null) {
deps.clearActivePlayback();
return;
}
if (
const withinStartupGrace =
typeof playback.stopReportsAfterMs === 'number' &&
Number.isFinite(playback.stopReportsAfterMs) &&
(deps.getNow?.() ?? Date.now()) < playback.stopReportsAfterMs
) {
(deps.getNow?.() ?? Date.now()) < playback.stopReportsAfterMs;
if (playback.loadedMediaPath === null) {
// Playback is armed before `loadfile`, so an empty path this soon belongs to the file
// being replaced and the new item's path is still coming. Later, the load never happened.
if (!withinStartupGrace) deps.clearActivePlayback();
return;
}
if (withinStartupGrace) return;
// Clear before any network call so progress ticks fired during the stop find nothing to
// report, then let reports already in flight finish so none can arrive after the stop.
deps.clearActivePlayback();
await deps.reportTracker?.settled();
// Only this playback's reports: mpv may already be reporting the next episode.
await deps.reportTracker?.settled(playback);
try {
const observedPositionSeconds = await readMpvPositionSecondsOrFallback(deps.getMpvClient());
// mpv may have moved to another file while reports drained, and its position would then
// overwrite this item's resume point. Off its file, the last position observed for it
// (cached on every time-pos update) stands in.
const mpvClient = deps.getMpvClient();
const stillOnItem =
Boolean(playback.loadedMediaPath) &&
mpvClient?.currentVideoPath?.trim() === playback.loadedMediaPath?.trim();
const observedPositionSeconds = stillOnItem
? await readMpvPositionSecondsOrFallback(mpvClient)
: 0;
const positionSeconds = resolveReportablePositionSeconds(playback, observedPositionSeconds);
const positionTicks = secondsToJellyfinTicks(positionSeconds, deps.ticksPerSecond);
try {
await playback.reporter.reportProgress({
itemId: playback.itemId,
mediaSourceId: playback.mediaSourceId,
positionTicks,
isPaused: false,
playMethod: playback.playMethod,
audioStreamIndex: playback.audioStreamIndex,
subtitleStreamIndex: playback.subtitleStreamIndex,
eventName: 'TimeUpdate',
});
} catch (error) {
deps.logDebug('Failed to report Jellyfin remote final progress', error);
}
const reported = await playback.reporter.reportStopped({
itemId: playback.itemId,
mediaSourceId: playback.mediaSourceId,
positionTicks,
failed: false,
playMethod: playback.playMethod,
audioStreamIndex: playback.audioStreamIndex,
subtitleStreamIndex: playback.subtitleStreamIndex,
eventName: 'stop',
});
if (reported === false) {
deps.logWarn?.(
`Jellyfin did not accept the playback stop report for item ${playback.itemId}; the server may keep showing it as playing.`,
);
}
await sendJellyfinStopReports(deps, playback, positionSeconds);
} catch (error) {
deps.logDebug('Failed to report Jellyfin remote stop', error);
}
};
}
/**
* Reports the stop of a playback mpv has already left for another playlist entry. mpv's position
* now belongs to the new file, so the stop carries the last position observed for this one.
* The caller has already replaced the active playback.
*/
export function createReportSupersededJellyfinPlaybackHandler(
deps: JellyfinStopReportDeps & { reportTracker?: JellyfinRemoteReportTracker },
) {
return async (playback: ActiveJellyfinRemotePlaybackState): Promise<void> => {
// Only this playback's reports: the new one keeps reporting and must not hold the stop.
await deps.reportTracker?.settled(playback);
try {
await sendJellyfinStopReports(deps, playback, playback.lastKnownPositionSeconds ?? 0);
} catch (error) {
deps.logDebug('Failed to report Jellyfin remote stop', error);
}
@@ -225,17 +225,19 @@ test('media path change handler schedules character dictionary once per media pa
);
});
test('media path change handler marks Jellyfin remote playback loaded from media path', () => {
test('media path change handler hands the path to Jellyfin before the immersion sync', () => {
const calls: string[] = [];
const handler = createHandleMpvMediaPathChangeHandler(
createMediaPathDeps(calls, {
markJellyfinRemotePlaybackLoaded: (path) => calls.push(`jellyfin-loaded:${path}`),
handleJellyfinMediaPathLoaded: (path) => calls.push(`jellyfin-loaded:${path}`),
}),
);
handler({ path: 'https://stream.example/video.m3u8' });
assert.ok(calls.includes('jellyfin-loaded:https://stream.example/video.m3u8'));
const loadedAt = calls.indexOf('jellyfin-loaded:https://stream.example/video.m3u8');
assert.ok(loadedAt >= 0);
assert.ok(loadedAt < calls.indexOf('sync'));
assert.equal(calls.includes('stopped'), false);
});
+6 -2
View File
@@ -69,7 +69,7 @@ export function createHandleMpvMediaPathChangeHandler(deps: {
syncImmersionMediaState: () => void;
scheduleCharacterDictionarySync?: () => void;
signalAutoplayReadyIfWarm?: (path: string) => void;
markJellyfinRemotePlaybackLoaded?: (path: string) => void;
handleJellyfinMediaPathLoaded?: (path: string) => void;
flushPlaybackPositionOnMediaPathClear?: (mediaPath: string) => void;
refreshDiscordPresence: () => void;
}) {
@@ -94,9 +94,13 @@ export function createHandleMpvMediaPathChangeHandler(deps: {
deps.maybeProbeAnilistDuration(mediaKey);
deps.ensureAnilistMediaGuess(mediaKey);
}
// Runs before the immersion sync: a Jellyfin episode mpv started from its playlist records
// its stats metadata here, and the session that sync starts must already see it.
if (trimmedPath.length > 0) {
deps.handleJellyfinMediaPathLoaded?.(normalizedPath);
}
deps.syncImmersionMediaState();
if (trimmedPath.length > 0) {
deps.markJellyfinRemotePlaybackLoaded?.(normalizedPath);
if (trimmedPath !== lastCharacterDictionarySyncMediaPath) {
lastCharacterDictionarySyncMediaPath = trimmedPath;
deps.scheduleCharacterDictionarySync?.();
@@ -82,7 +82,7 @@ export function createMpvMainEventBindingDeps(deps: {
ensureAnilistMediaGuess: (mediaKey: string) => void;
syncImmersionMediaState: () => void;
signalAutoplayReadyIfWarm?: (path: string) => void;
markJellyfinRemotePlaybackLoaded?: (path: string) => void;
handleJellyfinMediaPathLoaded?: (path: string) => void;
scheduleCharacterDictionarySync?: () => void;
updateCurrentMediaTitle: (title: string) => void;
resetAnilistMediaGuessState: () => void;
@@ -329,8 +329,7 @@ export function createMpvMainEventBindingDeps(deps: {
ensureAnilistMediaGuess: (mediaKey: string) => deps.ensureAnilistMediaGuess(mediaKey),
syncImmersionMediaState: () => deps.syncImmersionMediaState(),
signalAutoplayReadyIfWarm: (path: string) => deps.signalAutoplayReadyIfWarm?.(path),
markJellyfinRemotePlaybackLoaded: (path: string) =>
deps.markJellyfinRemotePlaybackLoaded?.(path),
handleJellyfinMediaPathLoaded: (path: string) => deps.handleJellyfinMediaPathLoaded?.(path),
scheduleCharacterDictionarySync: () => deps.scheduleCharacterDictionarySync?.(),
updateCurrentMediaTitle: (title: string) => deps.updateCurrentMediaTitle(title),
resetAnilistMediaGuessState: () => deps.resetAnilistMediaGuessState(),
+2 -2
View File
@@ -65,7 +65,7 @@ export function createBindMpvMainEventHandlersHandler(deps: {
ensureAnilistMediaGuess: (mediaKey: string) => void;
syncImmersionMediaState: () => void;
signalAutoplayReadyIfWarm?: (path: string) => void;
markJellyfinRemotePlaybackLoaded?: (path: string) => void;
handleJellyfinMediaPathLoaded?: (path: string) => void;
flushPlaybackPositionOnMediaPathClear?: (mediaPath: string) => void;
updateCurrentMediaTitle: (title: string) => void;
@@ -148,7 +148,7 @@ export function createBindMpvMainEventHandlersHandler(deps: {
flushPlaybackPositionOnMediaPathClear: (mediaPath) =>
deps.flushPlaybackPositionOnMediaPathClear?.(mediaPath),
signalAutoplayReadyIfWarm: (path) => deps.signalAutoplayReadyIfWarm?.(path),
markJellyfinRemotePlaybackLoaded: (path) => deps.markJellyfinRemotePlaybackLoaded?.(path),
handleJellyfinMediaPathLoaded: (path) => deps.handleJellyfinMediaPathLoaded?.(path),
scheduleCharacterDictionarySync: () => deps.scheduleCharacterDictionarySync?.(),
refreshDiscordPresence: () => deps.refreshDiscordPresence(),
});