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

Jellyfin playback now keeps the episodes around the playing one in mpv's
playlist, so mpv's playlist keys and end-of-file advance move through the
series (across seasons) in the same mpv and app session.

- Queue neighbors only after the first time-pos, so startup is not slowed.
- Adopt queued entries on mpv's path change without a loadfile: report the
  previous item stopped, then start reporting, stats, and subtitles for the
  new one. Runs before the immersion sync so stats metadata is recorded first.
- Tell the mpv plugin which playlist paths the app manages so start-file
  skips subtitle rearm and overlay auto-start for them.
- Add jellyfin.episodePlaylist.enabled (default on) and maxEpisodes
  (default 5, clamped 2-25), a rolling window centered on the current episode,
  under Settings > Integrations > Jellyfin > Episode Playlist.
- Add a fake-Jellyfin e2e scenario covering next/prev in one session.
This commit is contained in:
sudacode committed 2026-11-23 01:13:33 -08:00
1 parent 93045ebf9f
commit 8076f3faae
41 files changed
+1450 -149

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
import { once } from 'node:events';
import fs from 'node:fs';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
export type FakeJellyfinEpisode = { id: string; name: string; mediaPath: string };
export type FakeJellyfinReport = {
kind: 'playing' | 'progress' | 'stopped';
itemId: string;
positionTicks: number;
};
export type FakeJellyfin = {
url: string;
userId: string;
accessToken: string;
/** Every playback report the app sent, in arrival order. */
reports: FakeJellyfinReport[];
stop: () => Promise<void>;
};
const SERIES_ID = 'e2e-series';
const REPORT_KINDS: Record<string, FakeJellyfinReport['kind']> = {
'/Sessions/Playing': 'playing',
'/Sessions/Playing/Progress': 'progress',
'/Sessions/Playing/Stopped': 'stopped',
};
// Serves one file with Range support, since mpv probes and seeks over HTTP.
function serveFile(request: http.IncomingMessage, response: http.ServerResponse, file: string) {
const size = fs.statSync(file).size;
const range = /^bytes=(\d+)-(\d*)$/.exec(request.headers.range ?? '');
const start = range ? Number(range[1]) : 0;
const end = range?.[2] ? Number(range[2]) : size - 1;
response.writeHead(range ? 206 : 200, {
'content-type': 'video/x-matroska',
'accept-ranges': 'bytes',
'content-length': end - start + 1,
...(range ? { 'content-range': `bytes ${start}-${end}/${size}` } : {}),
});
fs.createReadStream(file, { start, end }).pipe(response);
}
/**
* A Jellyfin stand-in holding one series of `episodes`, in order. It answers the item, episode
* list, PlaybackInfo, and stream requests direct play needs, and records playback reports.
*/
export async function startFakeJellyfin(episodes: FakeJellyfinEpisode[]): Promise<FakeJellyfin> {
const reports: FakeJellyfinReport[] = [];
const byId = new Map(episodes.map((episode, index) => [episode.id, { episode, index }]));
const itemJson = (id: string) => {
const found = byId.get(id);
if (!found) return null;
return {
Id: id,
Name: found.episode.name,
Type: 'Episode',
SeriesName: 'E2E Show',
SeriesId: SERIES_ID,
ParentIndexNumber: 1,
IndexNumber: found.index + 1,
LocationType: 'FileSystem',
UserData: { PlaybackPositionTicks: 0 },
MediaSources: [
{
Id: id,
Container: 'mkv',
SupportsDirectStream: true,
SupportsTranscoding: false,
MediaStreams: [],
},
],
};
};
const server = http.createServer((request, response) => {
const url = new URL(request.url ?? '/', 'http://fake-jellyfin');
const json = (status: number, body: unknown) => {
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
};
const stream = /^\/Videos\/([^/]+)\/stream$/.exec(url.pathname);
if (request.method === 'GET' && stream) {
const found = byId.get(stream[1]!);
if (!found) return json(404, {});
return serveFile(request, response, found.episode.mediaPath);
}
const chunks: Buffer[] = [];
request.on('data', (chunk: Buffer) => chunks.push(chunk));
request.on('end', () => {
const reportKind = REPORT_KINDS[url.pathname];
if (request.method === 'POST' && reportKind) {
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
reports.push({
kind: reportKind,
itemId: String(body.ItemId ?? ''),
positionTicks: Number(body.PositionTicks ?? 0),
});
response.writeHead(204);
return response.end();
}
const item = /^\/Users\/[^/]+\/Items\/([^/]+)$/.exec(url.pathname);
if (request.method === 'GET' && item) {
const body = itemJson(item[1]!);
return body ? json(200, body) : json(404, {});
}
const playbackInfo = /^\/Items\/([^/]+)\/PlaybackInfo$/.exec(url.pathname);
if (request.method === 'POST' && playbackInfo) {
return json(200, { MediaSources: itemJson(playbackInfo[1]!)?.MediaSources ?? [] });
}
if (request.method === 'GET' && url.pathname === `/Shows/${SERIES_ID}/Episodes`) {
return json(200, { Items: episodes.map((episode) => itemJson(episode.id)) });
}
json(404, {});
});
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address() as AddressInfo;
return {
url: `http://127.0.0.1:${port}`,
userId: 'e2e-user',
accessToken: 'e2e-token',
reports,
stop: async () => {
server.closeAllConnections();
server.close();
await once(server, 'close');
},
};
}
+3
View File
@@ -30,6 +30,8 @@ export type E2eSessionOptions = {
config?: JsonObject;
/** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */
files?: Record<string, string>;
/** Extra environment for every app launch, e.g. a Jellyfin session. */
env?: Record<string, string>;
};
export type AppTarget = {
@@ -241,6 +243,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
SUBMINER_APP_LOG: path.join(root, 'app.log'),
// Stay attached instead of re-spawning detached, so the harness owns the process.
SUBMINER_BACKGROUND_CHILD: '1',
...options.env,
},
unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'],
};
+112
View File
@@ -0,0 +1,112 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test, { after } from 'node:test';
import { startFakeJellyfin, type FakeJellyfin } from './harness/fake-jellyfin';
import { generateFixtureClip } from './harness/fixtures';
import { startE2eSession, type E2eSession } from './harness/session';
import { waitUntil } from './harness/wait';
const TEST_TIMEOUT_MS = 180_000;
const EPISODE_IDS = ['ep1', 'ep2', 'ep3'];
let clipsDir: string | undefined;
let jellyfin: FakeJellyfin | undefined;
let session: E2eSession | undefined;
after(async () => {
await session?.dispose();
await jellyfin?.stop();
if (clipsDir) fs.rmSync(clipsDir, { recursive: true, force: true });
});
type PlaylistEntry = { filename: string; current?: boolean };
// The episode ids in mpv's playlist, the current one marked with `*`.
async function playlistIds(mpv: E2eSession['mpv']): Promise<string[]> {
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
return playlist.map((entry) => {
const id = /\/Videos\/([^/]+)\/stream/.exec(entry.filename)?.[1] ?? entry.filename;
return entry.current ? `${id}*` : id;
});
}
async function mainPid(started: E2eSession): Promise<number> {
const main = await started.mainProcess();
try {
return await main.evaluate<number>('process.pid');
} finally {
main.close();
}
}
test(
'Jellyfin playback moves through queued series episodes in the same session',
{ timeout: TEST_TIMEOUT_MS },
async () => {
clipsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-e2e-jellyfin-'));
const episodes = EPISODE_IDS.map((id, index) => ({
id,
name: `Episode ${index + 1}`,
mediaPath: path.join(clipsDir!, `${id}.mkv`),
}));
await Promise.all(episodes.map((episode) => generateFixtureClip(episode.mediaPath)));
jellyfin = await startFakeJellyfin(episodes);
session = await startE2eSession({
config: {
jellyfin: {
enabled: true,
serverUrl: jellyfin.url,
remoteControlEnabled: false,
episodePlaylist: { enabled: true, maxEpisodes: 3 },
},
},
env: {
SUBMINER_JELLYFIN_ACCESS_TOKEN: jellyfin.accessToken,
SUBMINER_JELLYFIN_USER_ID: jellyfin.userId,
},
});
const { mpv } = session;
const pid = await mainPid(session);
const reports = jellyfin.reports;
const reported = (kind: string, itemId: string) =>
reports.findIndex((report) => report.kind === kind && report.itemId === itemId);
await session.runAppCommand('--jellyfin-play', '--jellyfin-item-id=ep2');
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
description: 'the episodes around ep2 queued in the mpv playlist',
timeoutMs: 30_000,
});
assert.ok(reported('playing', 'ep2') >= 0, 'Jellyfin hears ep2 start');
await mpv.command('playlist-next');
await waitUntil(() => reported('playing', 'ep3') >= 0, {
description: 'Jellyfin to hear ep3 start after playlist-next',
timeoutMs: 30_000,
});
const stoppedEp2 = reported('stopped', 'ep2');
assert.ok(stoppedEp2 >= 0, 'Jellyfin hears ep2 stop');
assert.ok(stoppedEp2 < reported('playing', 'ep3'), 'ep2 stops before ep3 starts');
assert.equal(await mpv.command('get_property', 'media-title'), 'E2E Show S01E03 Episode 3');
// At the end of the series the window shifts back so it stays full.
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2,ep3*', {
description: 'the playlist window re-centered on ep3',
timeoutMs: 30_000,
});
await mpv.command('playlist-prev');
await waitUntil(
() =>
reports.filter((report) => report.kind === 'playing' && report.itemId === 'ep2').length ===
2,
{ description: 'Jellyfin to hear ep2 start again after playlist-prev', timeoutMs: 30_000 },
);
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
description: 'the playlist window re-centered on ep2',
timeoutMs: 30_000,
});
assert.equal(await mainPid(session), pid, 'the app keeps running across episode switches');
},
);