Compare commits

...
Author SHA1 Message Date
sudacode 935af26cca fix(jellyfin): keep episode titles from leaking across playlist entries
- Pass force-media-title as a per-file loadfile option for every Jellyfin play instead of setting it globally first
- Skip mpv media-title updates for Jellyfin videos in the immersion tracker so a stale title can't replace the canonical one
2026-11-23 03:07:32 -08:00
sudacode 24cd8cae88 fix(jellyfin): drain only the stopped playback's reports in the generic stop
The generic stop waited for every tracked report, including progress for
the next queued episode, which could delay the stop and the start waiting
on it. It now waits only for reports tagged with the playback it stops.
2026-11-23 02:27:54 -08:00
sudacode 0cae6b96fb fix(jellyfin): order episode start reports and guard stop positions
- Track each episode's start report: the playback's own stop waits for it,
  and the next start waits for every start and stop in flight, so Jellyfin
  never keeps an older episode as now-playing.
- The generic stop handler takes mpv's position only while mpv still has
  the stopped item loaded; otherwise it uses the item's last observed
  position, so a stop cannot overwrite the resume point with the next
  episode's position.
2026-11-23 02:13:38 -08:00
sudacode 172c771d97 fix(jellyfin): keep the episode playlist window at least 3 long
With a 2-episode window the episode just left falls outside the next
window, so a queue run could remove it while the user stepped back to it.
mpv's IPC cannot check-and-remove atomically; a window of 3 or more always
keeps both immediate neighbors, so removals stay two steps from the
playing entry. maxEpisodes now clamps to 3..25.
2026-11-23 02:03:11 -08:00
sudacode b0446833e6 fix(jellyfin): start queued episodes after every in-flight stop report
Past the startup grace, mpv's empty path between playlist files makes the
generic stop handler report the old episode, and the queued one is then
adopted with nothing to supersede. Its start report did not wait for that
stop, so Jellyfin could get playing(next) before stopped(previous) and
clear the new now-playing item (Windows E2E, and end-of-file auto-advance).
Both stop handlers now record their reports in one tracker, and an episode
start waits for all of them.
2026-11-23 01:57:30 -08:00
sudacode 86823aebe9 fix(jellyfin): keep in-window playlist entries in place when re-queueing
A queue run read mpv's playlist, then removed and re-added every neighbor.
A playlist-next/prev that landed between the read and the edits could
remove the entry mpv was just starting, sending playback back to the old
episode (macOS E2E). Entries still in the window now stay put; only
entries outside it are removed and only missing ones are resolved and
inserted, so a step touches just the far ends of the window.
2026-11-23 01:53:00 -08:00
sudacode 93d95538ae test(e2e): check Jellyfin playlist titles only on mpv 0.42+
playlist/N/title is read-only before mpv 0.42, so the CI runners on 0.41
keep listing stream URLs. Note the version requirement in the docs.
2026-11-23 01:42:30 -08:00
sudacode ec98118006 fix(jellyfin): keep playback armed across file unload and serialize episode stops
- An empty mpv path during the startup grace belongs to the file being
  replaced, so it no longer clears the new, not-yet-loaded playback. This
  dropped Jellyfin reporting (and the episode queue) whenever playback
  started while another file was playing, and failed E2E on all CI runners.
- Chain superseded stop reports so each episode start waits for every
  earlier stop, and skip starts a later switch already took over.
- Tag tracked reports with their playback so a superseded stop drains only
  its own in-flight progress, not the new episode's.
- E2E: clamp the fake server's range end and wait for the ep2 start report.
2026-11-23 01:36:01 -08:00
sudacode c742e9541c fix(jellyfin): title queued playlist entries instead of stream URLs
- Set playlist/N/title for the current and queued neighbor episodes so mpv's playlist doesn't show stream URLs that carry the API key
- Thread the plan title through prepared Jellyfin playback
- Cover titles in unit and e2e playlist tests
2026-11-23 01:20:54 -08:00
sudacode 8076f3faae 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.
2026-11-23 01:13:33 -08:00
45 changed files with 1958 additions and 182 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
type: added
area: jellyfin
- Jellyfin playback now adds the episodes around the playing one to mpv's playlist, so mpv's playlist keys and end-of-file advance move through the series (across seasons) in the same session, with resume, progress reporting, stats, and subtitles handled per episode.
- New `jellyfin.episodePlaylist.enabled` (on by default) and `jellyfin.episodePlaylist.maxEpisodes` settings, under Settings > Integrations > Jellyfin > Episode Playlist.
@@ -0,0 +1,4 @@
type: fixed
area: jellyfin
- Starting Jellyfin playback while another file was playing could drop the new item's playback tracking, so Jellyfin never received its progress or stop reports. mpv's unload of the previous file no longer cancels the new playback.
+5 -1
View File
@@ -1111,7 +1111,11 @@
"mp3",
"aac"
], // Container allowlist for direct play decisions.
"transcodeVideoCodec": "h264" // Preferred transcode video codec when direct play is unavailable.
"transcodeVideoCodec": "h264", // Preferred transcode video codec when direct play is unavailable.
"episodePlaylist": {
"enabled": true, // Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes. Values: true | false
"maxEpisodes": 5 // Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).
} // Episode playlist setting.
}, // Optional Jellyfin integration for auth, browsing, and playback launch.
// ==========================================
+14 -12
View File
@@ -559,18 +559,20 @@ In external-profile mode, SubMiner only reads the profile. It does not open its
Log in to a Jellyfin server, browse libraries, and play or cast to SubMiner. Login tokens are stored encrypted, not in this file. See [Jellyfin integration](/jellyfin-integration).
| Key | Default | What it does |
| ----------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------- |
| `jellyfin.enabled` | `false` | Enable Jellyfin |
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner |
| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup (also needs `startupWarmups.jellyfinRemoteSession`) |
| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect |
| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers |
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding |
| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding |
| Key | Default | What it does |
| -------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `jellyfin.enabled` | `false` | Enable Jellyfin |
| `jellyfin.serverUrl` | `""` | Server URL, for example `http://localhost:8096` |
| `jellyfin.username` | `""` | Default username for `subminer jellyfin -l` |
| `jellyfin.remoteControlEnabled` | `true` | Let Jellyfin apps cast to SubMiner |
| `jellyfin.remoteControlAutoConnect` | `true` | Connect the cast session on startup (also needs `startupWarmups.jellyfinRemoteSession`) |
| `jellyfin.autoAnnounce` | `false` | Announce SubMiner as a cast target on connect |
| `jellyfin.pullPictures` | `false` | Fetch posters for launcher pickers |
| `jellyfin.iconCacheDir` | `"/tmp/subminer-jellyfin-icons"` | Poster cache folder |
| `jellyfin.directPlayPreferred` | `true` | Try direct play before transcoding |
| `jellyfin.transcodeVideoCodec` | `"h264"` | Codec requested when transcoding |
| `jellyfin.episodePlaylist.enabled` | `true` | Queue the episodes around the playing one in mpv's playlist ([episode playlist](/jellyfin-integration#episode-playlist)) |
| `jellyfin.episodePlaylist.maxEpisodes` | `5` | Most episodes in that playlist, the playing one included (3-25) |
### Discord rich presence
+18 -8
View File
@@ -27,6 +27,14 @@ If an episode has no Japanese subtitles, you can [generate them with Whisper](/s
Casting finds mpv through `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then `PATH`. On macOS it then checks `/opt/homebrew/bin/mpv`, `/usr/local/bin/mpv`, and `/Applications/mpv.app`, because an app opened from Finder, the Dock, or Spotlight does not get your shell's `PATH`. If mpv lives somewhere else, set `mpv.executablePath` to its full path (`command -v mpv` prints it). An invalid `mpv.executablePath` stops mpv from starting.
## Episode playlist
When you play an episode, by casting or from the terminal, SubMiner adds the episodes around it from the same series to mpv's playlist. Move between them with mpv's playlist keys (`<` and `>` by default) or your playlist UI, and mpv moves on to the next episode when one ends. The series order runs across seasons. Each switch happens in the running mpv and overlay; nothing restarts.
SubMiner waits until the first episode is playing before it looks up the others, so startup is no slower. Every episode you switch to reports progress like one you picked yourself, and resumes from the position Jellyfin had saved when it was added to the playlist. Its subtitles load the same way. With mpv 0.42 or newer, the playlist lists the queued episodes by title; older mpv versions show their stream URLs.
`episodePlaylist.maxEpisodes` caps how many episodes the playlist holds, centered on the playing one. Turn `episodePlaylist.enabled` off to play one episode at a time. Changes apply from the next episode switch.
## Playing from the terminal
The launcher can browse your libraries and play an item without a Jellyfin client:
@@ -42,14 +50,16 @@ Sign in first. Playback resumes from Jellyfin's saved position, and watch progre
All options are under **Settings > Integrations > Jellyfin**, or `jellyfin` in `config.jsonc`. See [Configuration](/configuration#jellyfin) for the full list and defaults.
| Key | What it does |
| -------------------------- | ---------------------------------------------------------------------- |
| `enabled` | Turns the integration on. Set for you when you sign in. |
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
| `remoteControlEnabled` | Lets SubMiner act as a cast target. |
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. |
| Key | What it does |
| ----------------------------- | ---------------------------------------------------------------------- |
| `enabled` | Turns the integration on. Set for you when you sign in. |
| `serverUrl` | Your Jellyfin server. Filled in when you sign in. |
| `remoteControlEnabled` | Lets SubMiner act as a cast target. |
| `remoteControlAutoConnect` | Connects at startup when `startupWarmups.jellyfinRemoteSession` is on. |
| `autoAnnounce` | Re-announces the device on connect. Try it if SubMiner appears late. |
| `transcodeVideoCodec` | Video codec requested when Jellyfin transcodes. |
| `episodePlaylist.enabled` | Adds the surrounding episodes to mpv's playlist. |
| `episodePlaylist.maxEpisodes` | Most episodes in that playlist, the playing one included. |
For headless setups, `SUBMINER_JELLYFIN_ACCESS_TOKEN` and `SUBMINER_JELLYFIN_USER_ID` supply a session without the sign-in window. Treat the token store and `config.jsonc` as secrets.
+1 -1
View File
@@ -124,7 +124,7 @@ script-message subminer-start backend=hyprland socket=/custom/path texthooker=no
`log-level` sets SubMiner's log verbosity. Do not use `--debug` for this; it turns on the app's dev mode.
The plugin also handles messages the SubMiner app sends it (`subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv).
The plugin also handles messages the SubMiner app sends it (`subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-managed-playlist-entries`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, `subminer-reload-session-bindings`). You do not need to send these yourself. The AniSkip messages are listed on the [AniSkip page](/aniskip-integration#triggering-from-mpv).
## Auto-start behavior
+5 -1
View File
@@ -1111,7 +1111,11 @@
"mp3",
"aac"
], // Container allowlist for direct play decisions.
"transcodeVideoCodec": "h264" // Preferred transcode video codec when direct play is unavailable.
"transcodeVideoCodec": "h264", // Preferred transcode video codec when direct play is unavailable.
"episodePlaylist": {
"enabled": true, // Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes. Values: true | false
"maxEpisodes": 5 // Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).
} // Episode playlist setting.
}, // Optional Jellyfin integration for auth, browsing, and playback launch.
// ==========================================
+1 -1
View File
@@ -227,7 +227,7 @@ The mpv plugin accepts these script messages:
script-message subminer-start backend=hyprland socket=/custom/path texthooker=no log-level=debug
```
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
The plugin also registers `subminer-autoplay-ready`, `subminer-autoplay-hold`, `subminer-visible-overlay-shown`, `subminer-visible-overlay-hidden`, `subminer-managed-subtitles-loading`, `subminer-managed-playlist-entries`, `subminer-overlay-loading-ready`, `subminer-overlay-loading-dismissed`, and `subminer-reload-session-bindings`. The SubMiner app sends these to keep the plugin in sync, so do not send them from your own scripts.
While the app is connected to mpv, it also handles two AniSkip messages over the mpv IPC socket: `subminer-skip-intro` skips the intro or outro that is playing, and `subminer-aniskip-refresh` reloads intro and outro data, for example after your script changes title or episode metadata.
+1
View File
@@ -73,6 +73,7 @@ Read when: you need to find the owner module for a behavior or test surface
- TMDB live-action metadata: `src/core/services/tmdb/` (client + exact-title resolver), `src/core/services/immersion-tracker/live-action-link.ts` (links an entry to a TMDB title and merges other holders of the same title). The AniList cover-art fetcher calls the resolver as its fallback; `imm_anime.media_kind` marks the result and keeps the entry out of AniList season repair.
- Jellyfin integration: `src/core/services/jellyfin*.ts`, `src/main/runtime/composers/jellyfin-*`,
assembled by `src/main/assemblies/jellyfin.ts`
The episode playlist (`jellyfin-episode-playlist.ts`) inserts the playing episode's series neighbors into mpv's playlist after the item's first time-pos, so it never delays startup. mpv starts those entries itself; `adoptQueuedEpisode` in `jellyfin-playback-launch.ts` recognizes them from mpv's `path` and switches Jellyfin reporting, stats metadata, and subtitles without a `loadfile`. It runs from the media-path handler before the immersion sync, because stats metadata must exist before the session starts. The `subminer-managed-playlist-entries` script message tells the plugin which paths the app manages, so its start-file handling skips subtitle rearm and overlay auto-start for them.
- YouTube playback, subtitles, media cache, and in-app browser: `src/core/services/youtube/`,
`src/main/runtime/youtube-*`, assembled by `src/main/assemblies/youtube.ts`
- User plugins: `src/core/services/plugins/` (host, `ctx`, `exec`), `src/main/runtime/plugin-panel-runtime.ts` (panel modal), `src/main/runtime/plugin-window-runtime.ts` (plugin windows), assembled by `src/main/assemblies/plugins.ts`; `src/renderer/modals/plugin-panel*.ts`; examples in `assets/plugins/`
+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 = Math.min(range?.[2] ? Number(range[2]) : size - 1, 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'],
};
+142
View File
@@ -0,0 +1,142 @@
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; title?: string };
// 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;
});
}
// `playlist/N/title` is writable from mpv 0.42.
async function supportsPlaylistTitles(mpv: E2eSession['mpv']): Promise<boolean> {
const version = String(await mpv.command('get_property', 'mpv-version'));
const [major = 0, minor = 0] = (/v?(\d+)\.(\d+)/.exec(version) ?? []).slice(1).map(Number);
return major > 0 || minor >= 42;
}
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,
});
// The start report is fire-and-forget, so it can land after the playlist fills.
await waitUntil(() => reported('playing', 'ep2') >= 0, {
description: 'Jellyfin to hear ep2 start',
timeoutMs: 30_000,
});
// mpv's playlist lists entry titles, not stream URLs carrying the API key. Entry titles
// became writable in mpv 0.42; older players keep listing URLs.
const titles = [
'E2E Show S01E01 Episode 1',
'E2E Show S01E02 Episode 2',
'E2E Show S01E03 Episode 3',
];
if (await supportsPlaylistTitles(mpv)) {
await waitUntil(
async () => {
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
return playlist.map((entry) => entry.title).join('|') === titles.join('|');
},
{
description: 'queued playlist entries titled like the playing episode',
timeoutMs: 10_000,
},
);
}
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');
},
);
+11 -1
View File
@@ -210,8 +210,17 @@ function M.create(ctx)
})
end
local function is_app_managed_playlist_entry()
local path = mp.get_property("path")
local managed_paths = state.app_managed_playlist_paths or {}
return type(path) == "string" and managed_paths[path] == true
end
local function on_start_file()
if should_show_overlay_loading_osd() then
if is_app_managed_playlist_entry() then
state.skip_managed_subtitle_rearm_once = true
state.app_managed_playback_pending = true
elseif should_show_overlay_loading_osd() then
process.start_overlay_loading_osd()
end
if state.pending_reload_media_identity ~= nil then
@@ -322,6 +331,7 @@ function M.create(ctx)
state.pending_reload_reason = nil
state.app_managed_playback_pending = false
state.app_managed_playback_active = false
state.app_managed_playlist_paths = {}
end
local function register_lifecycle_hooks()
+9
View File
@@ -27,6 +27,15 @@ function M.create(ctx)
state.skip_managed_subtitle_rearm_once = true
state.app_managed_playback_pending = true
end)
-- Playlist entries the app queued (Jellyfin neighbor episodes). mpv starts them on its own,
-- so start-file recognizes them by path instead of waiting for subminer-managed-subtitles-loading.
mp.register_script_message("subminer-managed-playlist-entries", function(...)
local paths = {}
for _, path in ipairs({ ... }) do
paths[path] = true
end
state.app_managed_playlist_paths = paths
end)
mp.register_script_message("subminer-menu", function()
ui.show_menu()
end)
+1
View File
@@ -34,6 +34,7 @@ function M.new()
pending_reload_reason = nil,
app_managed_playback_pending = false,
app_managed_playback_active = false,
app_managed_playlist_paths = {},
auto_start_retry_generation = 0,
session_binding_generation = 0,
session_binding_names = {},
+59
View File
@@ -1042,6 +1042,65 @@ do
)
end
do
local scenario = {
process_list = "",
option_overrides = {
binary_path = binary_path,
auto_start = "yes",
auto_start_visible_overlay = "yes",
auto_start_pause_until_ready = "yes",
socket_path = "/tmp/subminer-socket",
},
input_ipc_server = "/tmp/subminer-socket",
path = "https://jellyfin.example/Videos/ep1/stream",
media_title = "Jellyfin Episode 1",
files = {
[binary_path] = true,
},
}
local recorded, err = run_plugin_scenario(scenario)
assert_true(recorded ~= nil, "plugin failed to load for managed playlist entry scenario: " .. tostring(err))
recorded.script_messages["subminer-managed-playlist-entries"](
"https://jellyfin.example/Videos/ep1/stream",
"https://jellyfin.example/Videos/ep2/stream"
)
fire_event(recorded, "end-file", { reason = "eof" })
scenario.path = "https://jellyfin.example/Videos/ep2/stream"
scenario.media_title = "Jellyfin Episode 2"
fire_event(recorded, "start-file")
fire_event(recorded, "file-loaded")
assert_true(
not has_property_set(recorded.property_sets, "sid", "auto"),
"an app-queued playlist entry should keep the app's subtitle selection"
)
assert_true(
count_start_calls(recorded.async_calls) == 0,
"an app-queued playlist entry should not auto-start the overlay"
)
assert_true(
count_property_set(recorded.property_sets, "pause", true) == 0,
"an app-queued playlist entry should not arm the plugin pause gate"
)
assert_true(
not has_osd_message(recorded.osd, "SubMiner: Overlay loading |"),
"an app-queued playlist entry should not show the overlay loading spinner"
)
fire_event(recorded, "end-file", { reason = "stop" })
scenario.path = "/media/local-episode.mkv"
scenario.media_title = "Local Episode"
fire_event(recorded, "start-file")
fire_event(recorded, "file-loaded")
assert_true(
count_property_set(recorded.property_sets, "sid", "auto") == 1,
"a path the app did not queue should get the normal subtitle rearm"
)
assert_true(
count_start_calls(recorded.async_calls) == 1,
"a path the app did not queue should auto-start the overlay"
)
end
do
local recorded, err = run_plugin_scenario({
process_list = "",
@@ -160,6 +160,10 @@ export const INTEGRATIONS_DEFAULT_CONFIG: Pick<
directPlayPreferred: true,
directPlayContainers: ['mkv', 'mp4', 'webm', 'mov', 'flac', 'mp3', 'aac'],
transcodeVideoCodec: 'h264',
episodePlaylist: {
enabled: true,
maxEpisodes: 5,
},
},
discordPresence: {
enabled: true,
@@ -704,6 +704,20 @@ export function buildIntegrationConfigOptionRegistry(
defaultValue: defaultConfig.jellyfin.transcodeVideoCodec,
description: 'Preferred transcode video codec when direct play is unavailable.',
},
{
path: 'jellyfin.episodePlaylist.enabled',
kind: 'boolean',
defaultValue: defaultConfig.jellyfin.episodePlaylist.enabled,
description:
"Add the playing episode's neighbors from its Jellyfin series to the mpv playlist, so mpv's playlist controls and end-of-file advance move between episodes.",
},
{
path: 'jellyfin.episodePlaylist.maxEpisodes',
kind: 'number',
defaultValue: defaultConfig.jellyfin.episodePlaylist.maxEpisodes,
description:
'Most episodes kept in the mpv playlist, the playing one included, centered on it (3-25).',
},
{
path: 'discordPresence.enabled',
kind: 'boolean',
+8 -3
View File
@@ -62,9 +62,14 @@ export function getConfigHotReloadField(path: string): string | null {
// These consumers read the current config when the next operation starts.
if (
['jimaku', 'tmdb', 'subsync', 'notifications', 'subtitleGeneration'].some((root) =>
pathStartsWith(path, root),
)
[
'jimaku',
'tmdb',
'subsync',
'notifications',
'subtitleGeneration',
'jellyfin.episodePlaylist',
].some((root) => pathStartsWith(path, root))
) {
return path;
}
+43
View File
@@ -372,6 +372,49 @@ export function applyIntegrationConfig(context: ResolveContext): void {
);
}
if (isObject(src.jellyfin.episodePlaylist)) {
const episodePlaylist = src.jellyfin.episodePlaylist;
const playlistEnabled = asBoolean(episodePlaylist.enabled);
if (playlistEnabled !== undefined) {
resolved.jellyfin.episodePlaylist.enabled = playlistEnabled;
} else if (episodePlaylist.enabled !== undefined) {
warn(
'jellyfin.episodePlaylist.enabled',
episodePlaylist.enabled,
resolved.jellyfin.episodePlaylist.enabled,
'Expected boolean.',
);
}
const maxEpisodes = asNumber(episodePlaylist.maxEpisodes);
if (maxEpisodes !== undefined) {
const normalized = Math.min(25, Math.max(3, Math.floor(maxEpisodes)));
if (normalized !== maxEpisodes) {
warn(
'jellyfin.episodePlaylist.maxEpisodes',
episodePlaylist.maxEpisodes,
normalized,
'Out of range; clamped to 3..25.',
);
}
resolved.jellyfin.episodePlaylist.maxEpisodes = normalized;
} else if (episodePlaylist.maxEpisodes !== undefined) {
warn(
'jellyfin.episodePlaylist.maxEpisodes',
episodePlaylist.maxEpisodes,
resolved.jellyfin.episodePlaylist.maxEpisodes,
'Expected number.',
);
}
} else if (src.jellyfin.episodePlaylist !== undefined) {
warn(
'jellyfin.episodePlaylist',
src.jellyfin.episodePlaylist,
resolved.jellyfin.episodePlaylist,
'Expected object.',
);
}
if (Array.isArray(src.jellyfin.recentServers)) {
const seenRecentServers = new Set<string>();
resolved.jellyfin.recentServers = src.jellyfin.recentServers
+23
View File
@@ -165,3 +165,26 @@ test('yomitan externalProfilePath expands leading tilde to the current home dire
path.join(homeDir, '.config', 'gsm_overlay'),
);
});
test('jellyfin episodePlaylist resolves the toggle and clamps the episode cap', () => {
const { context, warnings } = createResolveContext({
jellyfin: {
episodePlaylist: { enabled: false, maxEpisodes: 400 },
},
});
applyIntegrationConfig(context);
assert.deepEqual(context.resolved.jellyfin.episodePlaylist, { enabled: false, maxEpisodes: 25 });
assert.ok(warnings.some((warning) => warning.path === 'jellyfin.episodePlaylist.maxEpisodes'));
});
test('jellyfin episodePlaylist raises an episode cap below 3', () => {
const { context } = createResolveContext({
jellyfin: { episodePlaylist: { maxEpisodes: 2 } },
});
applyIntegrationConfig(context);
assert.equal(context.resolved.jellyfin.episodePlaylist.maxEpisodes, 3);
});
+4
View File
@@ -223,6 +223,7 @@ const SUBSECTION_ORDER = new Map<string, number>(
'Toggle & Visibility',
'Open Panels',
'Playback',
'Episode Playlist',
'Default Fold State',
].map((subsection, index) => [subsection, index]),
);
@@ -629,6 +630,9 @@ function subsectionForPath(path: string): string | undefined {
if (path === 'mpv.aniskipButtonKey') {
return 'Playback';
}
if (path.startsWith('jellyfin.episodePlaylist.')) {
return 'Episode Playlist';
}
if (path.startsWith('shortcuts.')) {
const leaf = path.split('.').at(-1) ?? '';
if (
@@ -2949,6 +2949,38 @@ test('Jellyfin metadata refresh preserves a manual episode assignment', async ()
}
});
test('mpv media-title updates do not overwrite a Jellyfin video title', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
try {
const Ctor = await loadTrackerCtor();
tracker = new Ctor({ dbPath });
const streamUrl = 'http://jellyfin.local/Videos/item-3/stream?static=true&api_key=token';
tracker.recordJellyfinPlaybackMetadata({
mediaPath: streamUrl,
displayTitle: 'Show S01E03 Third',
itemTitle: 'Third',
seriesTitle: 'Show',
seasonNumber: 1,
episodeNumber: 3,
itemId: 'item-3',
});
tracker.handleMediaChange(streamUrl, 'Show S01E03 Third');
// mpv restores the previous episode's title as it leaves this playlist entry.
tracker.handleMediaTitleUpdate('Show S01E02 Second');
tracker.handleMediaChange(streamUrl, 'Show S01E02 Second');
const row = (tracker as unknown as { db: DatabaseSync }).db
.prepare('SELECT canonical_title AS title FROM imm_videos')
.get() as { title: string };
assert.equal(row.title, 'Show S01E03 Third');
} finally {
tracker?.destroy();
cleanupDbPath(dbPath);
}
});
test('startup repairs existing Jellyfin stream video links to metadata rows', async () => {
const dbPath = makeDbPath();
let tracker: ImmersionTrackerService | null = null;
@@ -2464,6 +2464,9 @@ export class ImmersionTrackerService {
private updateVideoTitleForActiveSession(canonicalTitle: string): void {
if (!this.sessionState) return;
// Jellyfin's title is authoritative. mpv's media-title can still name the previous playlist
// entry while it switches files, so it must not overwrite a Jellyfin video's title.
if (this.hasJellyfinMetadata(this.sessionState.videoId)) return;
updateVideoTitleRecord(this.db, this.sessionState.videoId, canonicalTitle);
}
}
+1
View File
@@ -128,6 +128,7 @@ export {
authenticateWithPassword as authenticateWithPasswordRuntime,
listItems as listJellyfinItemsRuntime,
listLibraries as listJellyfinLibrariesRuntime,
listSeriesEpisodeIds as listJellyfinSeriesEpisodeIdsRuntime,
listSubtitleTracks as listJellyfinSubtitleTracksRuntime,
resolvePlaybackPlan as resolveJellyfinPlaybackPlanRuntime,
ticksToSeconds as jellyfinTicksToSecondsRuntime,
+35
View File
@@ -4,6 +4,7 @@ import {
authenticateWithPassword,
listItems,
listLibraries,
listSeriesEpisodeIds,
listSubtitleTracks,
resolvePlaybackPlan,
ticksToSeconds,
@@ -886,3 +887,37 @@ test('toJellyfinOriginalStreamUrl maps direct and transcoded playback to the ori
assert.equal(toJellyfinOriginalStreamUrl('https://jf/Videos/item-1/stream', 'item-1'), null);
assert.equal(toJellyfinOriginalStreamUrl('/media/item-1.mkv', 'item-1'), null);
});
test('listSeriesEpisodeIds returns playable episodes in series order', async () => {
const originalFetch = globalThis.fetch;
let requestedUrl = '';
globalThis.fetch = (async (input) => {
requestedUrl = String(input);
return new Response(
JSON.stringify({
Items: [
{ Id: 'ep-1', LocationType: 'FileSystem' },
{ Id: 'ep-2', LocationType: 'Virtual' },
{ Id: 'ep-3', LocationType: 'FileSystem' },
{ Name: 'no id' },
],
}),
{ status: 200 },
);
}) as typeof fetch;
try {
const ids = await listSeriesEpisodeIds(
{ serverUrl: 'http://jellyfin.local', accessToken: 'token', userId: 'u1', username: 'kyle' },
clientInfo,
'series-1',
);
assert.deepEqual(ids, ['ep-1', 'ep-3']);
const url = new URL(requestedUrl);
assert.equal(url.pathname, '/Shows/series-1/Episodes');
assert.equal(url.searchParams.get('UserId'), 'u1');
assert.equal(url.searchParams.get('IsMissing'), 'false');
} finally {
globalThis.fetch = originalFetch;
}
});
+32
View File
@@ -29,6 +29,8 @@ export interface JellyfinPlaybackPlan {
title: string;
itemTitle: string;
seriesTitle: string | null;
/** Set for episodes; lets playback queue the series' neighboring episodes. */
seriesId: string | null;
seasonNumber: number | null;
episodeNumber: number | null;
startTimeTicks: number;
@@ -89,6 +91,8 @@ interface JellyfinItem {
Name?: string;
Type?: string;
SeriesName?: string;
SeriesId?: string;
LocationType?: string;
ParentIndexNumber?: number;
IndexNumber?: number;
UserData?: JellyfinItemUserData;
@@ -579,6 +583,7 @@ export async function resolvePlaybackPlan(
title: getDisplayTitle(item),
itemTitle,
seriesTitle,
seriesId: item.Type === 'Episode' ? ensureString(item.SeriesId).trim() || null : null,
seasonNumber: item.Type === 'Episode' ? asIntegerOrNull(item.ParentIndexNumber) : null,
episodeNumber: item.Type === 'Episode' ? asIntegerOrNull(item.IndexNumber) : null,
startTimeTicks,
@@ -611,6 +616,33 @@ export async function resolvePlaybackPlan(
};
}
/**
* Lists a series' episode ids in playback order. The order runs across season boundaries and
* skips episodes the server only knows from metadata.
*/
export async function listSeriesEpisodeIds(
session: JellyfinAuthSession,
client: JellyfinClientInfo,
seriesId: string,
): Promise<string[]> {
const query = new URLSearchParams({
UserId: session.userId,
IsMissing: 'false',
EnableImages: 'false',
EnableUserData: 'false',
});
const payload = await jellyfinRequestJson<JellyfinItemsResponse>(
`/Shows/${encodeURIComponent(seriesId)}/Episodes?${query.toString()}`,
{ method: 'GET' },
session,
client,
);
return (Array.isArray(payload.Items) ? payload.Items : [])
.filter((item) => item.LocationType !== 'Virtual')
.map((item) => ensureString(item.Id))
.filter((id) => id.length > 0);
}
export function ticksToSeconds(ticks: number): number {
return Math.max(0, Math.floor(ticks / JELLYFIN_TICKS_PER_SECOND));
}
+18
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';
@@ -140,6 +142,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
runJellyfinCommand,
openJellyfinSetupWindow,
ensureMpvConnectedForPlayback,
playJellyfinItemInMpv,
} = composeJellyfinRuntimeHandlers({
getResolvedJellyfinConfigMainDeps: {
getResolvedConfig: () => configService.getConfig(),
@@ -237,6 +240,7 @@ export function createJellyfinAssembly(deps: JellyfinAssemblyDeps) {
setTimeout(callback, delayMs);
},
convertTicksToSeconds: (ticks) => jellyfinTicksToSecondsRuntime(ticks),
getActivePlayback: () => activeJellyfinRemotePlayback,
setActivePlayback: (state) => {
activeJellyfinRemotePlayback = {
...(state as ActiveJellyfinRemotePlaybackState),
@@ -270,6 +274,11 @@ 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') ?? [],
logDebug: (message, error) => logger.debug(message, error),
},
remoteComposerOptions: {
getConfiguredSession: () => getConfiguredJellyfinSession(getResolvedJellyfinConfig()),
@@ -452,6 +461,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,222 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createJellyfinEpisodePlaylist,
selectEpisodeWindow,
type JellyfinEpisodePlaylistSettings,
type JellyfinPlaylistEntry,
} 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),
loadfileOptions: `opts-${itemId}`,
title: `Show ${itemId}`,
});
/** mpv's playlist, kept in sync with the commands the queue sends. */
function makeHarness(
settings: JellyfinEpisodePlaylistSettings = { enabled: true, maxEpisodes: 3 },
) {
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),
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 });
}
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, 'opts-e4'],
['loadfile', url('e2'), 'insert-at', 0, 'opts-e2'],
],
);
assert.deepEqual(harness.commands.at(-1), [
'script-message',
'subminer-managed-playlist-entries',
url('e3'),
url('e4'),
url('e2'),
]);
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, 'opts-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);
});
@@ -0,0 +1,221 @@
/** 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, applied whenever mpv starts this entry. */
loadfileOptions: string;
/** Shown in mpv's playlist, which otherwise lists the stream URL and its API key. */
title: string;
};
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>;
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 });
// Each insert is followed by its title, sent while the entry is still at that index.
const insertEntry = (entry: Entry, index: number) => {
deps.sendMpvCommand([
'loadfile',
entry.playbackUrl,
'insert-at',
index,
entry.loadfileOptions,
]);
deps.sendMpvCommand(['set_property', `playlist/${index}/title`, entry.title]);
model.splice(index, 0, entry.itemId);
nextQueued.set(entry.playbackUrl, { context, entry });
};
const currentAt = windowIds.indexOf(current.itemId);
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 windowIds.slice(currentAt + 1)) {
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 windowIds.slice(0, currentAt).reverse()) {
const entry = prepared.get(itemId);
if (model.includes(itemId)) anchor = model.indexOf(itemId);
else if (entry) insertEntry(entry, anchor);
}
queued = nextQueued;
deps.sendMpvCommand([
'script-message',
MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE,
...queued.keys(),
]);
}
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,32 @@ 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 () => [],
showMpvOsd: () => {},
logDebug: () => {},
...options.deps,
});
return {
handler,
commands,
events,
activeStates,
reports,
reporter,
reporters,
reporterParams,
play: (params: Partial<PlayParams> = {}) =>
handler({
@@ -141,19 +159,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,9 +313,11 @@ 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',
),
);
});
@@ -355,7 +374,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'],
);
});
+278 -75
View File
@@ -1,7 +1,14 @@
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 {
createJellyfinEpisodePlaylist,
type JellyfinEpisodePlaylistSettings,
} from './jellyfin-episode-playlist';
import type {
ActiveJellyfinRemotePlaybackState,
JellyfinPlaybackReporterLike,
} from './jellyfin-remote-commands';
type JellyfinClientInfo = {
clientName: string;
@@ -9,6 +16,12 @@ type JellyfinClientInfo = {
deviceId: string;
};
type JellyfinPlaybackContext = {
session: JellyfinAuthSession;
clientInfo: JellyfinClientInfo;
jellyfinConfig: JellyfinConfig;
};
type ActivePlaybackState = {
itemId: string;
reporter: JellyfinPlaybackReporterLike;
@@ -104,14 +117,92 @@ function resolveEffectiveStartTimeTicks(
return Math.max(0, planStartTimeTicks);
}
/** A resolved Jellyfin item in the form mpv loads it. */
type JellyfinPreparedPlayback = {
itemId: string;
seriesId: string | null;
title: string;
plan: JellyfinPlaybackPlan;
playbackUrl: string;
loadfileOptions: string;
startTimeTicks: number;
startSeconds: number;
playMethod: 'DirectPlay' | 'Transcode';
};
// mpv's `%<bytes>%value` quoting takes any value verbatim, commas and colons included.
function quoteMpvOptionValue(value: string): string {
return `%${Buffer.byteLength(value, 'utf8')}%${value}`;
}
// 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 buildJellyfinLoadfileOptions(plan: JellyfinPlaybackPlan, startSeconds: number): string {
const options = [...JELLYFIN_LOADFILE_SUBTITLE_SUPPRESSION_OPTIONS];
if (plan.mode === 'direct' && startSeconds > 0) {
options.push(`start=${startSeconds}`);
}
options.push(`force-media-title=${quoteMpvOptionValue(plan.title)}`);
return options.join(',');
}
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),
loadfileOptions: buildJellyfinLoadfileOptions(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 +225,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 +234,142 @@ 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>;
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 {
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(),
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) {
@@ -182,74 +393,66 @@ export function createPlayJellyfinItemInMpvHandler(deps: {
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,
};
// `loadfile replace` empties mpv's playlist, taking 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]);
deps.sendMpvCommand([
'loadfile',
prepared.playbackUrl,
'replace',
-1,
prepared.loadfileOptions,
]);
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(),
});
+4
View File
@@ -389,6 +389,10 @@ export interface ResolvedConfig {
directPlayPreferred: boolean;
directPlayContainers: string[];
transcodeVideoCodec: string;
episodePlaylist: {
enabled: boolean;
maxEpisodes: number;
};
};
discordPresence: {
enabled: boolean;
+4
View File
@@ -93,6 +93,10 @@ export interface JellyfinConfig {
directPlayPreferred?: boolean;
directPlayContainers?: string[];
transcodeVideoCodec?: string;
episodePlaylist?: {
enabled?: boolean;
maxEpisodes?: number;
};
}
export type DiscordPresenceStylePreset = 'default' | 'meme' | 'japanese' | 'minimal';