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

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

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

No files matched your search

+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.
+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 (2-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 (2-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 resumes from Jellyfin's saved position and reports progress like one you picked yourself. Its subtitles load the same way.
`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 (2-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 = range?.[2] ? Number(range[2]) : size - 1;
response.writeHead(range ? 206 : 200, {
'content-type': 'video/x-matroska',
'accept-ranges': 'bytes',
'content-length': end - start + 1,
...(range ? { 'content-range': `bytes ${start}-${end}/${size}` } : {}),
});
fs.createReadStream(file, { start, end }).pipe(response);
}
/**
* A Jellyfin stand-in holding one series of `episodes`, in order. It answers the item, episode
* list, PlaybackInfo, and stream requests direct play needs, and records playback reports.
*/
export async function startFakeJellyfin(episodes: FakeJellyfinEpisode[]): Promise<FakeJellyfin> {
const reports: FakeJellyfinReport[] = [];
const byId = new Map(episodes.map((episode, index) => [episode.id, { episode, index }]));
const itemJson = (id: string) => {
const found = byId.get(id);
if (!found) return null;
return {
Id: id,
Name: found.episode.name,
Type: 'Episode',
SeriesName: 'E2E Show',
SeriesId: SERIES_ID,
ParentIndexNumber: 1,
IndexNumber: found.index + 1,
LocationType: 'FileSystem',
UserData: { PlaybackPositionTicks: 0 },
MediaSources: [
{
Id: id,
Container: 'mkv',
SupportsDirectStream: true,
SupportsTranscoding: false,
MediaStreams: [],
},
],
};
};
const server = http.createServer((request, response) => {
const url = new URL(request.url ?? '/', 'http://fake-jellyfin');
const json = (status: number, body: unknown) => {
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
};
const stream = /^\/Videos\/([^/]+)\/stream$/.exec(url.pathname);
if (request.method === 'GET' && stream) {
const found = byId.get(stream[1]!);
if (!found) return json(404, {});
return serveFile(request, response, found.episode.mediaPath);
}
const chunks: Buffer[] = [];
request.on('data', (chunk: Buffer) => chunks.push(chunk));
request.on('end', () => {
const reportKind = REPORT_KINDS[url.pathname];
if (request.method === 'POST' && reportKind) {
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
reports.push({
kind: reportKind,
itemId: String(body.ItemId ?? ''),
positionTicks: Number(body.PositionTicks ?? 0),
});
response.writeHead(204);
return response.end();
}
const item = /^\/Users\/[^/]+\/Items\/([^/]+)$/.exec(url.pathname);
if (request.method === 'GET' && item) {
const body = itemJson(item[1]!);
return body ? json(200, body) : json(404, {});
}
const playbackInfo = /^\/Items\/([^/]+)\/PlaybackInfo$/.exec(url.pathname);
if (request.method === 'POST' && playbackInfo) {
return json(200, { MediaSources: itemJson(playbackInfo[1]!)?.MediaSources ?? [] });
}
if (request.method === 'GET' && url.pathname === `/Shows/${SERIES_ID}/Episodes`) {
return json(200, { Items: episodes.map((episode) => itemJson(episode.id)) });
}
json(404, {});
});
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const { port } = server.address() as AddressInfo;
return {
url: `http://127.0.0.1:${port}`,
userId: 'e2e-user',
accessToken: 'e2e-token',
reports,
stop: async () => {
server.closeAllConnections();
server.close();
await once(server, 'close');
},
};
}
+3
View File
@@ -30,6 +30,8 @@ export type E2eSessionOptions = {
config?: JsonObject;
/** Files written before launch, keyed by path relative to the config dir (e.g. plugins). */
files?: Record<string, string>;
/** Extra environment for every app launch, e.g. a Jellyfin session. */
env?: Record<string, string>;
};
export type AppTarget = {
@@ -241,6 +243,7 @@ export async function startE2eSession(options: E2eSessionOptions = {}): Promise<
SUBMINER_APP_LOG: path.join(root, 'app.log'),
// Stay attached instead of re-spawning detached, so the harness owns the process.
SUBMINER_BACKGROUND_CHILD: '1',
...options.env,
},
unset: [...display.env.unset, 'ELECTRON_RUN_AS_NODE'],
};
+112
View File
@@ -0,0 +1,112 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test, { after } from 'node:test';
import { startFakeJellyfin, type FakeJellyfin } from './harness/fake-jellyfin';
import { generateFixtureClip } from './harness/fixtures';
import { startE2eSession, type E2eSession } from './harness/session';
import { waitUntil } from './harness/wait';
const TEST_TIMEOUT_MS = 180_000;
const EPISODE_IDS = ['ep1', 'ep2', 'ep3'];
let clipsDir: string | undefined;
let jellyfin: FakeJellyfin | undefined;
let session: E2eSession | undefined;
after(async () => {
await session?.dispose();
await jellyfin?.stop();
if (clipsDir) fs.rmSync(clipsDir, { recursive: true, force: true });
});
type PlaylistEntry = { filename: string; current?: boolean };
// The episode ids in mpv's playlist, the current one marked with `*`.
async function playlistIds(mpv: E2eSession['mpv']): Promise<string[]> {
const playlist = (await mpv.command('get_property', 'playlist')) as PlaylistEntry[];
return playlist.map((entry) => {
const id = /\/Videos\/([^/]+)\/stream/.exec(entry.filename)?.[1] ?? entry.filename;
return entry.current ? `${id}*` : id;
});
}
async function mainPid(started: E2eSession): Promise<number> {
const main = await started.mainProcess();
try {
return await main.evaluate<number>('process.pid');
} finally {
main.close();
}
}
test(
'Jellyfin playback moves through queued series episodes in the same session',
{ timeout: TEST_TIMEOUT_MS },
async () => {
clipsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'subminer-e2e-jellyfin-'));
const episodes = EPISODE_IDS.map((id, index) => ({
id,
name: `Episode ${index + 1}`,
mediaPath: path.join(clipsDir!, `${id}.mkv`),
}));
await Promise.all(episodes.map((episode) => generateFixtureClip(episode.mediaPath)));
jellyfin = await startFakeJellyfin(episodes);
session = await startE2eSession({
config: {
jellyfin: {
enabled: true,
serverUrl: jellyfin.url,
remoteControlEnabled: false,
episodePlaylist: { enabled: true, maxEpisodes: 3 },
},
},
env: {
SUBMINER_JELLYFIN_ACCESS_TOKEN: jellyfin.accessToken,
SUBMINER_JELLYFIN_USER_ID: jellyfin.userId,
},
});
const { mpv } = session;
const pid = await mainPid(session);
const reports = jellyfin.reports;
const reported = (kind: string, itemId: string) =>
reports.findIndex((report) => report.kind === kind && report.itemId === itemId);
await session.runAppCommand('--jellyfin-play', '--jellyfin-item-id=ep2');
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
description: 'the episodes around ep2 queued in the mpv playlist',
timeoutMs: 30_000,
});
assert.ok(reported('playing', 'ep2') >= 0, 'Jellyfin hears ep2 start');
await mpv.command('playlist-next');
await waitUntil(() => reported('playing', 'ep3') >= 0, {
description: 'Jellyfin to hear ep3 start after playlist-next',
timeoutMs: 30_000,
});
const stoppedEp2 = reported('stopped', 'ep2');
assert.ok(stoppedEp2 >= 0, 'Jellyfin hears ep2 stop');
assert.ok(stoppedEp2 < reported('playing', 'ep3'), 'ep2 stops before ep3 starts');
assert.equal(await mpv.command('get_property', 'media-title'), 'E2E Show S01E03 Episode 3');
// At the end of the series the window shifts back so it stays full.
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2,ep3*', {
description: 'the playlist window re-centered on ep3',
timeoutMs: 30_000,
});
await mpv.command('playlist-prev');
await waitUntil(
() =>
reports.filter((report) => report.kind === 'playing' && report.itemId === 'ep2').length ===
2,
{ description: 'Jellyfin to hear ep2 start again after playlist-prev', timeoutMs: 30_000 },
);
await waitUntil(async () => (await playlistIds(mpv)).join() === 'ep1,ep2*,ep3', {
description: 'the playlist window re-centered on ep2',
timeoutMs: 30_000,
});
assert.equal(await mainPid(session), pid, 'the app keeps running across episode switches');
},
);
+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 (2-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(2, Math.floor(maxEpisodes)));
if (normalized !== maxEpisodes) {
warn(
'jellyfin.episodePlaylist.maxEpisodes',
episodePlaylist.maxEpisodes,
normalized,
'Out of range; clamped to 2..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
+13
View File
@@ -165,3 +165,16 @@ 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'));
});
+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 (
+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);
@@ -5,6 +5,7 @@ import {
createJellyfinRemoteReportTracker,
createReportJellyfinRemoteProgressHandler,
createReportJellyfinRemoteStoppedHandler,
createReportSupersededJellyfinPlaybackHandler,
type JellyfinRemoteGeneralCommandHandlerDeps,
type JellyfinRemotePlayHandlerDeps,
type JellyfinRemotePlaystateHandlerDeps,
@@ -40,6 +41,9 @@ export type JellyfinRemoteComposerOptions = ComposerInputs<{
export type JellyfinRemoteComposerResult = ComposerOutputs<{
reportJellyfinRemoteProgress: ReturnType<typeof createReportJellyfinRemoteProgressHandler>;
reportJellyfinRemoteStopped: ReturnType<typeof createReportJellyfinRemoteStoppedHandler>;
reportJellyfinPlaybackSuperseded: ReturnType<
typeof createReportSupersededJellyfinPlaybackHandler
>;
handleJellyfinRemotePlay: (payload: RemotePlayPayload) => Promise<void>;
handleJellyfinRemotePlaystate: (payload: RemotePlaystatePayload) => Promise<void>;
handleJellyfinRemoteGeneralCommand: (payload: RemoteGeneralPayload) => Promise<void>;
@@ -71,10 +75,17 @@ export function composeJellyfinRemoteHandlers(
logWarn: options.logWarn,
reportTracker,
});
const reportJellyfinPlaybackSuperseded = createReportSupersededJellyfinPlaybackHandler({
ticksPerSecond: options.ticksPerSecond,
logDebug: options.logDebug,
logWarn: options.logWarn,
reportTracker,
});
return {
reportJellyfinRemoteProgress,
reportJellyfinRemoteStopped,
reportJellyfinPlaybackSuperseded,
handleJellyfinRemotePlay: createHandleJellyfinRemotePlay({
getConfiguredSession: options.getConfiguredSession,
getClientInfo: options.getClientInfo,
@@ -50,7 +50,7 @@ export type JellyfinRuntimeComposerOptions = ComposerInputs<{
>[0];
playJellyfinItemInMpvMainDeps: Omit<
PlayJellyfinItemMainDeps,
'ensureMpvConnectedForPlayback' | 'preloadExternalSubtitles'
'ensureMpvConnectedForPlayback' | 'preloadExternalSubtitles' | 'reportPlaybackSuperseded'
>;
remoteComposerOptions: Omit<
JellyfinRemoteComposerOptions,
@@ -157,11 +157,14 @@ 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),
});
const {
reportJellyfinRemoteProgress,
reportJellyfinRemoteStopped,
reportJellyfinPlaybackSuperseded,
handleJellyfinRemotePlay,
handleJellyfinRemotePlaystate,
handleJellyfinRemoteGeneralCommand,
@@ -0,0 +1,157 @@
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}`,
});
/** 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 }> = [];
const commands: Array<Array<string | number>> = [];
let episodeListCalls = 0;
const queue = createJellyfinEpisodePlaylist<null, Entry>({
getSettings: () => settings,
listSeriesEpisodeIds: async () => {
episodeListCalls += 1;
return EPISODES;
},
prepareEntry: async (_context, itemId) => entry(itemId),
readMpvPlaylist: async () => playlist.map((item) => ({ ...item })),
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 });
}
},
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,
filenames: () => playlist.map((item) => item.filename),
};
}
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.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.equal(harness.queue.find(url('e2')), null);
assert.equal(harness.episodeListCalls(), 1, 'series order is reused while navigating');
});
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,181 @@
/** 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;
};
export type JellyfinEpisodePlaylistSettings = {
enabled: boolean;
/** Most entries kept in mpv's playlist, the current one included. */
maxEpisodes: number;
};
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 prepareNeighbors(context: Context, itemIds: string[]): Promise<Entry[]> {
const slots: Array<Entry | null> = itemIds.map(() => null);
await Promise.all(
itemIds.map((itemId, index) =>
deps.prepareEntry(context, itemId).then(
(entry) => {
slots[index] = entry;
},
(error: unknown) => {
deps.logDebug(`Failed to prepare Jellyfin episode ${itemId} for the playlist`, error);
},
),
),
);
return slots.filter((entry): entry is Entry => entry !== null);
}
async function queueNeighbors(context: Context, current: Entry): Promise<void> {
const run = ++generation;
const settings = deps.getSettings();
let previous: Entry[] = [];
let next: Entry[] = [];
if (settings.enabled && current.seriesId) {
const episodeIds = await getSeriesEpisodeIds(context, current.seriesId);
const window = selectEpisodeWindow(episodeIds, current.itemId, settings.maxEpisodes);
[previous, next] = await Promise.all([
prepareNeighbors(context, window.previousIds),
prepareNeighbors(context, window.nextIds),
]);
}
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;
// Drop the entries queued for the last item, from the end so earlier indices stay valid.
// Entries still in the window are re-added below with fresh resume positions.
let currentAt = currentIndex;
for (let index = playlist.length - 1; index >= 0; index -= 1) {
if (index === currentIndex || !queued.has(playlist[index]!.filename)) continue;
deps.sendMpvCommand(['playlist-remove', index]);
if (index < currentIndex) currentAt -= 1;
}
queued = new Map([[current.playbackUrl, { context, entry: current }]]);
next.forEach((entry, offset) => {
deps.sendMpvCommand([
'loadfile',
entry.playbackUrl,
'insert-at',
currentAt + 1 + offset,
entry.loadfileOptions,
]);
queued.set(entry.playbackUrl, { context, entry });
});
// Each insert before the current entry pushes it one slot later.
previous.forEach((entry, offset) => {
deps.sendMpvCommand([
'loadfile',
entry.playbackUrl,
'insert-at',
currentAt + offset,
entry.loadfileOptions,
]);
queued.set(entry.playbackUrl, { context, entry });
});
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,7 @@ 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 } from './jellyfin-remote-commands';
type Deps = Parameters<typeof createPlayJellyfinItemInMpvHandler>[0];
type PlayParams = Parameters<ReturnType<typeof createPlayJellyfinItemInMpvHandler>>[0];
@@ -30,6 +31,7 @@ function makePlan(overrides: Partial<JellyfinPlaybackPlan> = {}): JellyfinPlayba
title: 'Episode 1',
itemTitle: 'Episode 1',
seriesTitle: null,
seriesId: null,
seasonNumber: null,
episodeNumber: null,
startTimeTicks: 0,
@@ -73,16 +75,23 @@ function makeHarness(options: { plan?: Partial<JellyfinPlaybackPlan>; deps?: Par
activeStates.push(state);
events.push(`active:${String(state.loadedMediaPath)}`);
},
getActivePlayback: () => null,
setLastProgressAtMs: () => {},
createPlaybackReporter: (params) => {
reporterParams.push(params);
return reporter;
},
reportPlaybackSuperseded: async () => {},
getEpisodePlaylistSettings: () => ({ enabled: true, maxEpisodes: 3 }),
listSeriesEpisodeIds: async () => [],
readMpvPlaylist: async () => [],
showMpvOsd: () => {},
logDebug: () => {},
...options.deps,
});
return {
handler,
commands,
events,
activeStates,
@@ -359,3 +368,135 @@ for (const c of HOOK_FAILURE_CASES) {
]);
});
}
/**
* 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[] = [];
let active: ActiveJellyfinRemotePlaybackState | null = null;
let releaseSupersededStop = () => {};
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 new Promise<void>((resolve) => {
releaseSupersededStop = resolve;
});
},
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,
active: () => active,
releaseSupersededStop: () => releaseSupersededStop(),
// 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.deepEqual(harness.superseded, ['item-1']);
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.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.equal(harness.handler.adoptQueuedEpisode(harness.streamUrl('item-2')), false);
assert.equal(harness.handler.adoptQueuedEpisode('https://elsewhere.example/video.mkv'), false);
});
+272 -74
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,100 @@ function resolveEffectiveStartTimeTicks(
return Math.max(0, planStartTimeTicks);
}
function buildJellyfinLoadfileOptions(plan: JellyfinPlaybackPlan, startSeconds: number): string {
/** A resolved Jellyfin item in the form mpv loads it. */
type JellyfinPreparedPlayback = {
itemId: string;
seriesId: string | null;
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}`;
}
function buildJellyfinLoadfileOptions(
plan: JellyfinPlaybackPlan,
startSeconds: number,
mediaTitle?: string,
): string {
const options = [...JELLYFIN_LOADFILE_SUBTITLE_SUPPRESSION_OPTIONS];
if (plan.mode === 'direct' && startSeconds > 0) {
options.push(`start=${startSeconds}`);
}
if (mediaTitle) {
options.push(`force-media-title=${quoteMpvOptionValue(mediaTitle)}`);
}
return options.join(',');
}
function prepareJellyfinPlayback(
itemId: string,
plan: JellyfinPlaybackPlan,
convertTicksToSeconds: (ticks: number) => number,
options: {
startTimeTicksOverride?: number;
fallbackToPlanStartTimeOnZeroOverride?: boolean;
// Playlist entries carry their title per file; an explicit play sets it before loadfile.
perFileMediaTitle?: 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,
plan,
playbackUrl: stripManagedSubtitleStreamFromPlaybackUrl(playbackUrlBase),
loadfileOptions: buildJellyfinLoadfileOptions(
plan,
startSeconds,
options.perFileMediaTitle ? plan.title : undefined,
),
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 +233,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 +242,125 @@ 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>;
/** 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,
{ perFileMediaTitle: true },
),
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,
previousStopReported: Promise<void> = Promise.resolve(),
): Promise<void> => {
const { plan } = prepared;
await awaitBestEffortPlaybackHook(() =>
deps.preloadExternalSubtitles({
session: context.session,
clientInfo: context.clientInfo,
itemId: prepared.itemId,
}),
);
deps.showVisibleOverlay();
pendingNeighborQueue = { context, prepared };
// Jellyfin clears a session's now-playing item on any stop, so the start must come after.
await previousStopReported;
void reporter.reportPlaying({
itemId: prepared.itemId,
mediaSourceId: undefined,
playMethod: prepared.playMethod,
positionTicks: prepared.startTimeTicks,
isPaused: false,
audioStreamIndex: plan.audioStreamIndex,
subtitleStreamIndex: plan.subtitleStreamIndex,
eventName: 'start',
});
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 +384,70 @@ 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);
const previousStopReported = previous
? deps.reportPlaybackSuperseded(previous).catch((error: unknown) => {
deps.logDebug('Failed to report the previous Jellyfin episode stopped', error);
})
: undefined;
void finishPlaybackStartup(queued.context, queued.entry, reporter, previousStopReported).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';
@@ -445,3 +446,40 @@ test('createReportJellyfinRemoteStoppedHandler clears playback before reporting
'stopped:cleared',
]);
});
test('createReportSupersededJellyfinPlaybackHandler stops at the last position observed for the item', async () => {
const events: string[] = [];
const tracker = createJellyfinRemoteReportTracker();
let finishInFlightProgress = () => {};
tracker.track(
new Promise<void>((resolve) => {
finishInFlightProgress = () => {
events.push('in-flight progress done');
resolve();
};
}),
);
const reportSuperseded = createReportSupersededJellyfinPlaybackHandler({
ticksPerSecond: TICKS_PER_SECOND,
logDebug: () => {},
reportTracker: tracker,
});
const reported = reportSuperseded(
makePlayback({
itemId: 'item-1',
lastKnownPositionSeconds: 1410,
reporter: makeReporter({
reportStopped: async (payload) => {
events.push(`stopped:${payload.itemId}@${payload.positionTicks}`);
},
}),
}),
);
await Promise.resolve();
assert.deepEqual(events, [], 'the stop waits for progress already in flight');
finishInFlightProgress();
await reported;
assert.deepEqual(events, ['in-flight progress done', 'stopped:item-1@14100000000']);
});
+62 -30
View File
@@ -208,6 +208,49 @@ 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();
@@ -230,36 +273,25 @@ export function createReportJellyfinRemoteStoppedHandler(deps: JellyfinRemoteSto
try {
const observedPositionSeconds = await readMpvPositionSecondsOrFallback(deps.getMpvClient());
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> => {
await deps.reportTracker?.settled();
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';